HttpClient的post方式:
package com.example.dugaolong.httpurlconnectiondemo;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.apache.http.HttpResponse;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by dugaolong on 16/5/16.
*/
public class HttpClientPostTest extends Activity {
private static final String TAG = Postactivity.class.getSimpleName();
private String postUrl = "http://172.16.150.82:8080/http/servlet/Http";
private Handler mHandler;
private TextView tv;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_httpclient_post);
button = (Button) findViewById(R.id.bt_post);
tv = (TextView) findViewById(R.id.tv_message);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
doPost();
}
});
mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what == 1){
Bundle bundle = msg.getData();
String res = bundle.getString("res");
// tv.setText(msg.obj.toString());
tv.setText(res);
}
}
};
}
/**
* 执行post方法
*/
private void doPost() {
new Thread(new Runnable() {
@Override
public void run() {
HttpPost httpPost = new HttpPost(postUrl);
HttpClient httpClient = new DefaultHttpClient();
try {
//创建参数列表
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sex","girl"));
//url格式编码
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(params,"UTF-8");
httpPost.setEntity(urlEncodedFormEntity);
//执行请求
HttpResponse httpResponse = httpClient.execute(httpPost);
//请求结果
if (httpResponse.getStatusLine().getStatusCode()==200){
String result = EntityUtils.toString(httpResponse.getEntity());
Message msg = new Message();
// msg.obj=result;
msg.what = 1;
Bundle bundle = new Bundle();
bundle.putString("res",result);
msg.setData(bundle);
mHandler.sendMessage(msg);
Log.i(TAG,"result:"+result);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}