一、需要用到的场景
在jQuery中使用$.post()就可以方便的发起一个post请求,在android程序中有时也要从服务器获取一些数据,就也必须得使用post请求了。
二、需要用到的主要类
在android中使用post请求主要要用到的类是HttpPost、HttpResponse、EntityUtils
三、主要思路
1、创建HttpPost实例,设置需要请求服务器的url。
2、为创建的HttpPost实例设置参数,参数设置时使用键值对的方式用到NameValuePair类。
3、发起post请求获取返回实例HttpResponse
4、使用EntityUtils对返回值的实体进行处理(可以取得返回的字符串,也可以取得返回的byte数组)
(httpResponse =new DefaultHttpClient().execute(httpPost)最好放在新线程里,否则会报错。也就是说没有thread的话会直接报错)
packagecom.example.posttest;
importjava.io.IOException;
importjava.util.ArrayList;
importjava.util.List;
importorg.apache.http.HttpResponse;
importorg.apache.http.NameValuePair;
importorg.apache.http.client.ClientProtocolException;
importorg.apache.http.client.entity.UrlEncodedFormEntity;
importorg.apache.http.client.methods.HttpPost;
importorg.apache.http.impl.client.DefaultHttpClient;
importorg.apache.http.message.BasicNameValuePair;
importorg.apache.http.protocol.HTTP;
importorg.apache.http.util.EntityUtils;
importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.util.Log;
importandroid.widget.TextView;
import android.widget.Toast;
publicclass MainActivity extends Activity {
TextView tView;
HttpPost httpPost;
HttpResponse httpResponse = null;
List<NameValuePair> params;
@Override
publicvoid onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
String url = "http://www.beijibear.com/android_post.php";
tView = (TextView) findViewById(R.id.textview1);
// 第一步,创建HttpPost对象
httpPost = new HttpPost(url);
// 设置HTTP POST请求参数必须用NameValuePair对象
params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", "beijibear"));
new Thread(){
publicvoid run() {
try {
// 设置httpPost请求参数
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
httpResponse = new DefaultHttpClient().execute(httpPost);
//System.out.println(httpResponse.getStatusLine().getStatusCode());
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 第三步,使用getEntity方法活得返回结果
String result = EntityUtils.toString(httpResponse.getEntity());
Log.i("test", result+"");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
};
}.start();
}
}
在POSTjson的时候,只需要用params.add(new BasicNameValuePair("参数", json数据))。
这只是单纯的post数据,但是实际应用中应该处理超时的情况。网上有关如下讲解:
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
httpResponse = client.execute(httpPost);
只需要进行几行代码处理即可,但是我并没有测试出来