您的位置:首页 > 理论基础 > 计算机网络

android网络编程 二(Apache HttpClient)

2016-01-17 20:34 651 查看
这里讲的是用HttpClient连接服务器

android端代码(get,post两种请求方式):

</pre><pre name="code" class="java">new Thread(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
//HttpGet请求
/*String path = "http://192.168.1.100:8080/TestAndroid/testServlet?name=zhangsan&age=23";
HttpGet get = new HttpGet(path);
HttpClient client = new DefaultHttpClient();
try {
HttpResponse response = client.execute(get);
Log.e("执行", "client.execute");
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity, "utf-8");
Log.e("entity content", content);
}

} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
//HttpPost请求
String path = "http://192.168.1.100:8080/TestAndroid/testServlet";
HttpPost post = new HttpPost(path);
HttpClient client = new DefaultHttpClient();

List<NameValuePair> pairs = new ArrayList<NameValuePair>();
NameValuePair pair1 = new BasicNameValuePair("name", "张三");
NameValuePair pair2 = new BasicNameValuePair("age", "23");
pairs.add(pair1);
pairs.add(pair2);

try {
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(pairs, "utf-8");
post.setEntity(urlEncodedFormEntity);
HttpResponse response = client.execute(post);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity, "utf-8");
Log.e("entity_content", content);
//							byte temp[]=str.getBytes("iso-8859-1");
//							s=new String(temp,"UTF-8");
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}){}.start();


显然HttpClient的方式比前面的HttpURLConnection更加简洁方便。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: