HttpClient的HttpGet和HttpPost访问网络
核心代码:
HttpClient
apache 发布,模拟一个浏览器
步骤:
1.打开浏览器
HttpClient client = new DefaultHttpClient()
2.输入一些内容
HttpGet
3.敲回车
client.execute(path);
1、HttpGet
/**
* 1、使用HttpClient——GET方式进行登录
*
* @throws IOException
*/
public static String loginByGet(String username, String password)throws IOException {
System.out.println("以GET方式提交。。。");
// 1、打开一个浏览器
HttpClient client = new DefaultHttpClient();
String path = "http://192.168.221.221:8080/web/LoginServlet?username="
+ username + "&password" + password;
// 2、输入url地址
HttpGet httpGet = new HttpGet(path);
// 3、敲回车
HttpResponse response = client.execute(httpGet);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
// 数据实体
HttpEntity entity = response.getEntity();
InputStream in = entity.getContent();
String text = StreamUtils.readStream(in);
return text;
}
return null;
}
2、HttpPost
/**
* 2、使用HttpClient——POST方式登录
*
* @param username
* @param password
* @return
* @throws IOException
*/
public static String loginByPost(String username, String password)
throws IOException {
System.out.println("以POST方式登录。。。");
String path = "http://192.168.221.221:8080/web/LoginServlet";
// 1、打开一个浏览器
HttpClient client = new DefaultHttpClient();
// 2、输入url地址
HttpPost httpPost = new HttpPost(path);
// 3、设置请求内容
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username", username));
parameters.add(new BasicNameValuePair("password", password));
HttpEntity entity = new UrlEncodedFormEntity(parameters, "UTF-8");
// 对请求参数进行编码:encoding the name/value pairs be encoded with
httpPost.setEntity(entity);
// 4、敲回车
HttpResponse response = client.execute(httpPost);
int code = response.getStatusLine().getStatusCode(); // 服务器状态码
if (code == 200) {
//把封装在返回体中的数据取出来
InputStream in = response.getEntity().getContent();
String text = StreamUtils.readStream(in);
return text;
}
return null;
}
注意事项
- get方式访问网络的时候的参数还是要组合到url地址后面的
- 不管get请求还是post请求返回来的数据都封装在HttpResponse对象中,然后通过这个方法的一系列 getXXX方法获取你想要的内容
使用到的重要api
- new DefaultHttpClient();获取一个HttpClient对象
- new HttpGet(path);//获得一个Httpget对象
- new HttpPost(path)//获得一个HttpPost对象
- client.execute(httpGet);//把get请求或者post请求提交到服务器,返回结果集
- setEntity(entity);使用post请求方式的时候用来设置请求体的数据的方法
- response.getStatusLine().getStatusCode(); //通过状态行对象来拿到服务器状态码
- response.getEntity().getContent();//通过返回体对象获取服务器返回的数据流对象
本文介绍了如何使用HttpClient通过GET和POST方式访问网络资源。包括创建HttpClient实例、构造HttpGet和HttpPost请求,以及如何处理响应数据。
658

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



