HttpClient与HttpURLConnection的请求方式
2013-01-11 11:11
381 查看
HttpURLConnection是java的标准类,HttpURLConnection继承自URLConnection,可用于向指定网站发送GET请求、POST请求。
/* *
*下面是httpURLConnection的post请求
* @param url 链接地址“http://host:8080/Login.ashx”
* @param params 上传参数
*/
public static String postRequst(String url, String params)
throws IOException {
//存放返回数据
String resultData = "";
//创建一个URL
URL posturl = null;
try {
posturl = new URL(url);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException");
}
if (posturl != null) {
//创建一个链接
HttpURLConnection urlConn = (HttpURLConnection) posturl .openConnection();
//设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false;
urlConn.setDoOutput(true);
// 设置是否从httpUrlConnection读入,默认情况下是true;
urlConn.setDoInput(true);
//设置请求方式,这里设置为POST请求
urlConn.setRequestMethod("POST");
//设置是否使用缓存,post请求不能使用缓存
urlConn.setUseCaches(false);
//设置只作用于当前的实例
urlConn.setInstanceFollowRedirects(true);
//设定传送的内容类型是可序列化的java对象
urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//连接
urlConn.connect();
//数据输出流,该语句隐含的执行connect动作
DataOutputStream out = new DataOutputStream( urlConn.getOutputStream());
//将参数写入流,刷新提交关闭流
out.writeBytes(params);
out.flush();
out.close();
//读取连接返回的数据
BufferedReader reader = new BufferedReader(new InputStreamReader( urlConn.getInputStream()));
String inputLine = null;
while (((inputLine = reader.readLine()) != null)) {
resultData += inputLine + "\n";
}
//关闭
reader.close();
urlConn.disconnect();
}
return resultData;
}
在一般情况下,如果只是需要Web站点的某个简单页面提交请求并获取服务器响应,HttpURLConnection完全可以胜任。但在绝大部分情况下,Web站点的网页可能没这么简单,这些页面并不是通过一个简单的URL就可访问的,可能需要用户登录而且具有相应的权限才可访问该页面。在这种情况下,就需要涉及Session、Cookie的处理了,如果打算使用HttpURLConnection来处理这些细节,当然也是可能实现的,只是处理起来难度就大了。
HttpClient更方便更强大的解决了HttpURLConnection能做到或者不能做到的事情,HttpClient模块提供的两大类HttpPost和HttpGet实现Http请求:
HttpPost —— 传送的数据量较大,一般被默认为不受限制。一般用于发送一些表单数据,传输数据更安全
HttpGet —— 传送的数据量较小,不能大于2KB。一般用于请求获取一些信息,执行效率更高
/**
* POST请求,上传表单
* @param url 链接地址“http://host:8080/Login.ashx”
* @param params 上传参数List
* @param str_agent 标识
* @return 返回获取的数据
*/
public static String postTableData(String url, List<NameValuePair> params,
String str_agent) throws ConnectTimeoutException,ClientProtocolException,
IOException, XmlPullParserException {
String result = null;HttpClient httpclient = createHttpClient();//
创建一个HttpClient
HttpPost httppost = new HttpPost(url);//
创建一个POST请求
httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));//
添加请求参数到请求对象
httppost.setHeader("User-Agent", str_agent);//在报文头部添加一些字符串标识
HttpResponse response = httpclient.execute(httppost);//发送请求
HttpEntity resEntity = response.getEntity();//从响应中获取消息实体
if (resEntity != null) {
result = EntityUtils.toString(resEntity);
}
httpclient.getConnectionManager().shutdown();//关闭连接
return result;
}
/**
* Get请求,下载数据
* @param url 链接地址“http://host:8080/GetList.ashx”
* @param params 上传参数List
* @param str_agent 标识
* @return 返回获取的数据
* /
public static String getListData(String url, List<NameValuePair> params,
String str_agent) throws ConnectTimeoutException,ClientProtocolException,
IOException, XmlPullParserException {
// 构建url
if (params != null) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < params.size(); i++) {
buf.append("&").append(params.get(i).getName()).append("=").append(params.get(i).getValue());
}
if (url.indexOf("?") != -1)// url已经有参数
{
url = url + buf.toString();
} else {
url = url + "?" + buf.toString();
}
}
String result = null; HttpClient httpclient = createHttpClient();//
创建一个HttpClient
HttpGet httpGet = new HttpGet(url);// 创建一个Get请求
httpGet.setHeader("User-Agent", str_agent);//在报文头部添加一些字符串标识
HttpResponse response = httpclient.execute(httpGet);//发送请求
HttpEntity resEntity = response.getEntity();//从响应中获取消息实体
if (resEntity != null) {
result = EntityUtils.toString(resEntity);
}
httpclient.getConnectionManager().shutdown();//关闭连接
return result;
}
/* *
*下面是httpURLConnection的post请求
* @param url 链接地址“http://host:8080/Login.ashx”
* @param params 上传参数
*/
public static String postRequst(String url, String params)
throws IOException {
//存放返回数据
String resultData = "";
//创建一个URL
URL posturl = null;
try {
posturl = new URL(url);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException");
}
if (posturl != null) {
//创建一个链接
HttpURLConnection urlConn = (HttpURLConnection) posturl .openConnection();
//设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false;
urlConn.setDoOutput(true);
// 设置是否从httpUrlConnection读入,默认情况下是true;
urlConn.setDoInput(true);
//设置请求方式,这里设置为POST请求
urlConn.setRequestMethod("POST");
//设置是否使用缓存,post请求不能使用缓存
urlConn.setUseCaches(false);
//设置只作用于当前的实例
urlConn.setInstanceFollowRedirects(true);
//设定传送的内容类型是可序列化的java对象
urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//连接
urlConn.connect();
//数据输出流,该语句隐含的执行connect动作
DataOutputStream out = new DataOutputStream( urlConn.getOutputStream());
//将参数写入流,刷新提交关闭流
out.writeBytes(params);
out.flush();
out.close();
//读取连接返回的数据
BufferedReader reader = new BufferedReader(new InputStreamReader( urlConn.getInputStream()));
String inputLine = null;
while (((inputLine = reader.readLine()) != null)) {
resultData += inputLine + "\n";
}
//关闭
reader.close();
urlConn.disconnect();
}
return resultData;
}
在一般情况下,如果只是需要Web站点的某个简单页面提交请求并获取服务器响应,HttpURLConnection完全可以胜任。但在绝大部分情况下,Web站点的网页可能没这么简单,这些页面并不是通过一个简单的URL就可访问的,可能需要用户登录而且具有相应的权限才可访问该页面。在这种情况下,就需要涉及Session、Cookie的处理了,如果打算使用HttpURLConnection来处理这些细节,当然也是可能实现的,只是处理起来难度就大了。
HttpClient更方便更强大的解决了HttpURLConnection能做到或者不能做到的事情,HttpClient模块提供的两大类HttpPost和HttpGet实现Http请求:
HttpPost —— 传送的数据量较大,一般被默认为不受限制。一般用于发送一些表单数据,传输数据更安全
HttpGet —— 传送的数据量较小,不能大于2KB。一般用于请求获取一些信息,执行效率更高
/**
* POST请求,上传表单
* @param url 链接地址“http://host:8080/Login.ashx”
* @param params 上传参数List
* @param str_agent 标识
* @return 返回获取的数据
*/
public static String postTableData(String url, List<NameValuePair> params,
String str_agent) throws ConnectTimeoutException,ClientProtocolException,
IOException, XmlPullParserException {
String result = null;HttpClient httpclient = createHttpClient();//
创建一个HttpClient
HttpPost httppost = new HttpPost(url);//
创建一个POST请求
httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));//
添加请求参数到请求对象
httppost.setHeader("User-Agent", str_agent);//在报文头部添加一些字符串标识
HttpResponse response = httpclient.execute(httppost);//发送请求
HttpEntity resEntity = response.getEntity();//从响应中获取消息实体
if (resEntity != null) {
result = EntityUtils.toString(resEntity);
}
httpclient.getConnectionManager().shutdown();//关闭连接
return result;
}
/**
* Get请求,下载数据
* @param url 链接地址“http://host:8080/GetList.ashx”
* @param params 上传参数List
* @param str_agent 标识
* @return 返回获取的数据
* /
public static String getListData(String url, List<NameValuePair> params,
String str_agent) throws ConnectTimeoutException,ClientProtocolException,
IOException, XmlPullParserException {
// 构建url
if (params != null) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < params.size(); i++) {
buf.append("&").append(params.get(i).getName()).append("=").append(params.get(i).getValue());
}
if (url.indexOf("?") != -1)// url已经有参数
{
url = url + buf.toString();
} else {
url = url + "?" + buf.toString();
}
}
String result = null; HttpClient httpclient = createHttpClient();//
创建一个HttpClient
HttpGet httpGet = new HttpGet(url);// 创建一个Get请求
httpGet.setHeader("User-Agent", str_agent);//在报文头部添加一些字符串标识
HttpResponse response = httpclient.execute(httpGet);//发送请求
HttpEntity resEntity = response.getEntity();//从响应中获取消息实体
if (resEntity != null) {
result = EntityUtils.toString(resEntity);
}
httpclient.getConnectionManager().shutdown();//关闭连接
return result;
}
相关文章推荐
- HttpClient、HttpUrlConnection请求数据的方式
- HttpClient 和 HttpURLConnection两种请求方式的写法
- HttpUrlConnection和HttpClient两种方式获取GET和POST请求
- Android 中的两种请求网络资源的方式:HttpClient和HttpURLConnection
- 安卓应用的HTTP请求方式:Apache HTTP Client和HttpURLConnection
- HttpURLConnection和HttpClient两种连接方式的区别
- HttpClient和HttpUrlConnection的请求网路
- HttpURLConnection的GET和POST请求方式
- Android4种网络连接方式HttpClient、HttpURLConnection、OKHttp和Volley优缺点和性能对比
- Android HTTP协议请求网络(三)之HttpURLConnection方式
- HttpURLConnection、HttpClient网络请求
- 网络请求部分-------HttpClient和HttpURLConnection
- 使用HttpURLConnection通过POST方式提交请求数据,并上传文件
- 使用HttpURLConnection采用get方式请求数据-----乱码问题
- HTTP访问的两种方式(HttpClient+HttpURLConnection)整合汇总对比
- Android4种网络连接方式HttpClient、HttpURLConnection、OKHttp和Volley优缺点和性能对比
- HttpClient和HttpURLConnection网络请求数据
- Android中的HttpURLConnection网络请求方式
- HttpURLConnection、HttpClient请求网络数据、Xutils的HttpUtils 请求数据
- 使用HttpURLConnection和使用HttpClient方式请求网络采用get方式和post方式请求数据