android网络编程 二(Apache HttpClient)


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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值