需要权限:
<uses-permission android:name="android.permission.INTERNET" />
package com.example.httppost;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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 android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
public class MainActivity extends Activity {
// URL地址
String url = "http://aaa.bb.cn/c.asmx/d";
HttpPost httpRequest = null;
List<NameValuePair> params = null;
HttpResponse httpResponse;
TextView tv = null;
private String strResult;
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 0x01) {
tv.setText(strResult);
}
};
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
// 建立HttpPost连接
httpRequest = new HttpPost(url);
// Post传参
params = new ArrayList<NameValuePair>();
// "键","值"
params.add(new BasicNameValuePair("sUser", "zheng"));
// 安卓4.0之后不能在主线程发送Http请求,所以开子线程
new Thread() {
public void run() {
try {
// 发出HTTP request
httpRequest.setEntity(new UrlEncodedFormEntity(params));
// 取得HTTP response
httpResponse = new DefaultHttpClient().execute(httpRequest);
// 若状态码为200
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 取出回应字符串
strResult = EntityUtils.toString(httpResponse
.getEntity());
// 子线程不能更改UI界面,所以通过handler
mHandler.sendEmptyMessage(0x01);
} else {
tv.setText("Error Response"
+ httpResponse.getStatusLine().toString());
}
} catch (Exception e) {
// TODO Auto-generated catch block
tv.setText(e.getMessage().toString());
}
};
}.start();
}
}