public class TestSendDataActivity extends Activity {
//请求地址的连接
String action="http://192.168.1.109:8088/EABox";
//发送post连接
HttpPost httpRequest=null;
//用来传递参数
List <NameValuePair> params=null;
//接收响应
HttpResponse httpResponse;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//建立HttpPost连接
httpRequest=new HttpPost(action);
//Post运作传送变数必须用NameValuePair[]阵列储存
params=new ArrayList<NameValuePair>();
//传递参数username是传递的自动,kobe要传递的值
params.add(new BasicNameValuePair("username","kobe"));
params.add(new BasicNameValuePair("password","12345"));
try {
//发出HTTP request
httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
//httpRequest.setEntity(new StringEntity(params.toString()));
//取得HTTP response
httpResponse=new DefaultHttpClient().execute(httpRequest);
Log.i("tag", "得到返回状态是:"+httpResponse.getStatusLine().getStatusCode());
//若状态码为200
if(httpResponse.getStatusLine().getStatusCode()==200){
//取出回应字串
String strResult=EntityUtils.toString(httpResponse.getEntity());
}else{
Log.i("tag", "没发送成功");
}
} catch (Exception e) {
Log.i("tag", "报错了"+e.getMessage().toString());
}
}
}
//请求地址的连接
String action="http://192.168.1.109:8088/EABox";
//发送post连接
HttpPost httpRequest=null;
//用来传递参数
List <NameValuePair> params=null;
//接收响应
HttpResponse httpResponse;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//建立HttpPost连接
httpRequest=new HttpPost(action);
//Post运作传送变数必须用NameValuePair[]阵列储存
params=new ArrayList<NameValuePair>();
//传递参数username是传递的自动,kobe要传递的值
params.add(new BasicNameValuePair("username","kobe"));
params.add(new BasicNameValuePair("password","12345"));
try {
//发出HTTP request
httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
//httpRequest.setEntity(new StringEntity(params.toString()));
//取得HTTP response
httpResponse=new DefaultHttpClient().execute(httpRequest);
Log.i("tag", "得到返回状态是:"+httpResponse.getStatusLine().getStatusCode());
//若状态码为200
if(httpResponse.getStatusLine().getStatusCode()==200){
//取出回应字串
String strResult=EntityUtils.toString(httpResponse.getEntity());
}else{
Log.i("tag", "没发送成功");
}
} catch (Exception e) {
Log.i("tag", "报错了"+e.getMessage().toString());
}
}
}
本文介绍了如何在Android应用中发送POST请求。通过创建HttpPost对象,设置请求地址,并使用NameValuePair列表传递参数,如username和password。然后使用DefaultHttpClient执行请求并检查响应状态,当状态码为200时,表示请求成功。
2219

被折叠的 条评论
为什么被折叠?



