这里讲的是用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更加简洁方便。
397

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



