码迷,mamicode.com
首页 > Web开发 > 详细

HttpClient4.x:Get和Post提交数据

时间:2015-08-11 20:49:53      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

一、Get提交方式

DefaultHttpClient httpclient = new DefaultHttpClient();
try {
//注:如果参数值为中文的话,提交过去后可能会是乱码
HttpGet httpget = new
HttpGet("http://www.xxx.com/x.jsp?username=zhangsan&age=20");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
//如果entity是流数据则关闭之
EntityUtils.consume(entity);
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}

二、Form表单Post提交方式

DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httpost = new HttpPost("http://www.xxx.com/x.jsp?");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
//提交两个参数及值
nvps.add(new BasicNameValuePair("age", "20"));
nvps.add(new BasicNameValuePair("username", "张三"));
//设置表单提交编码为UTF-8
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpResponse response = httpclient.execute(httpost);
HttpEntity entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
EntityUtils.consume(entity);
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}

在提交到的x.jsp中,我们还是像平常获取一个form表单数据那样处理就行了:

String username = request.getParameter("username");

 

HttpClient4.x:Get和Post提交数据

标签:

原文地址:http://www.cnblogs.com/ButterFuture/p/4721837.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!