首先在http://hc.apache.org/downloads.cgi下载HttpClient包
直接看代码
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView; import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils; import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List; public class MainActivity extends AppCompatActivity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 开启一个子线程,进行网络操作,等待有返回结果,使用handler通知UI
new Thread(networkTask).start(); } Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bundle data = msg.getData();
String val = data.getString("value");
Log.i("mylog", "请求结果为-->" + val);
// TODO
// UI界面的更新等相关操作
}
}; /**
* 网络操作相关的子线程
*/
Runnable networkTask = new Runnable() {
@Override
public void run() {
// TODO
// 在这里进行 http request.网络请求相关操作
String TAG = "ABC"; //baseUrl
String url = "http://192.168.8.7/insert.php"; HttpPost request = new HttpPost(url); //先将参数放入List,再对参数进行URL编码
List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("firstname", "这个是安卓"));
params.add(new BasicNameValuePair("lastname", "这是安卓加进去的"));
params.add(new BasicNameValuePair("age", "66")); try {
HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8"); request.setEntity(entity); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(request); Log.e(TAG, "Response Code: " +
response.getStatusLine().getStatusCode()); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String data = EntityUtils.toString(response.getEntity()); }
} catch (IOException e) {
Log.e(TAG, "~~~~~~"+e);
e.printStackTrace();
}
Message msg = new Message();
Bundle data = new Bundle();
data.putString("value", "请求结果");
msg.setData(data);
handler.sendMessage(msg);
}
}
}
需要注意的是http请求在安卓3.0后就不能放在MainTread中了