HttpURLConnection和HttpClient的简单用法
HttpURLConnection的简单用法:先通过一个URL创建一个conn对象,然后就是可以设置get或者是post方法,接着用流来读取响应结果即可
String html = null;
long startTime = System.currentTimeMillis();
try {
URL url = new URL("http://www.baidu.com/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET"); conn.setConnectTimeout(5 * 1000);
if (conn.getResponseCode() == 200) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) { html += line;
}
/*
//第二种方法
InputStream is = conn.getInputStream();
byte []buffer = new byte[is.available()];
is.read();
String result = new String(buffer);*/
} } catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
HttpClient的简单用法:
/**
* @param url
* @return 1.页面源码;2.TimeOut;3.没正确响应,返回null
*/
public String doHttpGet(String url) {
String result = null;
//通过url来创建httpGet对象
HttpGet httpGet = new HttpGet(url);
httpClient = new DefaultHttpClient();
// 请求超时
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);
// 读取超时
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,TIME_OUT);
try {
httpResponse = httpClient.execute(httpGet);
// 判断响应的状态码,200表示成功响应了请求
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 得到结果集
result = EntityUtils.toString(httpResponse.getEntity(),"GB2312");
// result = new String(result.getBytes(),"utf-8");
//System.out.println(result);
} else {
System.err.println("未得到正确的响应,响应吗:"+ httpResponse.getStatusLine().getStatusCode());
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
return "TimeOut";
}
return result;
} /**
* @param url
* @param paramsList
* @return 1.页面源码;2.TimeOut;3.没有响应,返回null
*/
public String doHttpPost(String url, List<NameValuePair> paramsList) {
String result = null;
// 根据url创建HttpPost实例
HttpPost httpPost = new HttpPost(url);
httpClient = new DefaultHttpClient();
// 请求超时
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);
// 读取超时
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,TIME_OUT);
try {
// 设置HttpPost请求参数必须用NameValuePair对象
httpPost.setEntity(new UrlEncodedFormEntity(paramsList, HTTP.UTF_8));
// 发送post请求
httpResponse = httpClient.execute(httpPost);
// 判断响应的状态码,200表示成功响应了请求
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(httpResponse.getEntity());
//System.out.println(result);
} else {
System.err.println("未得到正确的响应,响应吗:"+ httpResponse.getStatusLine().getStatusCode());
}
} catch (UnsupportedEncodingException e) {
System.out.println("UnsupportedEncodingException");
} catch (ParseException e) {
System.out.println("ParseException");
} catch (IOException e) {
return "TimeOut";
}
return result;
}
工具类NetManager:
package com.kale.mycmcc.net; import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils; public class NetManager {
public static int TIME_OUT = 4 * 1000; private HttpResponse httpResponse = null;
private HttpClient httpClient; /**
* @param url
* @return 1.页面源码;2.TimeOut;3.没正确响应,返回null
*/
public String doHttpGet(String url) {
String result = null;
//通过url来创建httpGet对象
HttpGet httpGet = new HttpGet(url);
httpClient = new DefaultHttpClient();
// 请求超时
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);
// 读取超时
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,TIME_OUT);
try {
httpResponse = httpClient.execute(httpGet);
// 判断响应的状态码,200表示成功响应了请求
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 得到结果集
result = EntityUtils.toString(httpResponse.getEntity(),"GB2312");
// result = new String(result.getBytes(),"utf-8");
//System.out.println(result);
} else {
System.err.println("未得到正确的响应,响应吗:"+ httpResponse.getStatusLine().getStatusCode());
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
return "TimeOut";
}
return result;
} /**
* @param url
* @param paramsList
* @return 1.页面源码;2.TimeOut;3.没有响应,返回null
*/
public String doHttpPost(String url, List<NameValuePair> paramsList) {
String result = null;
// 根据url创建HttpPost实例
HttpPost httpPost = new HttpPost(url);
httpClient = new DefaultHttpClient();
// 请求超时
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);
// 读取超时
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,TIME_OUT);
try {
// 设置HttpPost请求参数必须用NameValuePair对象
httpPost.setEntity(new UrlEncodedFormEntity(paramsList, HTTP.UTF_8));
// 发送post请求
httpResponse = httpClient.execute(httpPost);
// 判断响应的状态码,200表示成功响应了请求
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(httpResponse.getEntity());
//System.out.println(result);
} else {
System.err.println("未得到正确的响应,响应吗:"+ httpResponse.getStatusLine().getStatusCode());
}
} catch (UnsupportedEncodingException e) {
System.out.println("UnsupportedEncodingException");
} catch (ParseException e) {
System.out.println("ParseException");
} catch (IOException e) {
return "TimeOut";
}
return result;
} /* *//**
* 使用正则表达式过滤HTML标记
*//*
private String filterHtml(String source) {
if (null == source) {
return "";
}
return source.replaceAll("</?[^>]+>", "").trim();
} private void showToast(Context mContext, String message, int flag) {
Looper.prepare();
Toast.makeText(mContext, message, flag).show();
Looper.loop();
}*/ }
HttpURLConnection和HttpClient的简单用法的更多相关文章
- Android 中HttpURLConnection与HttpClient的简单使用
1:HttpHelper.java public class HttpHelper { //1:标准的Java接口 public static String getStringFromNet1(Str ...
- android 网络编程之HttpURLConnection与HttpClient使用与封装
1.写在前面 大部分andriod应用需要与服务器进行数据交互,HTTP.FTP.SMTP或者是直接基于SOCKET编程都可以进行数据交互,但是HTTP必然是使用最广泛的协议. 本文并 ...
- HttpURLConnection和HttpClient的区别2(转)
1.HttpClient比HttpURLConnection功能更强大,但是做java建议用前者,安卓建议用后者 2.这两者都支持HTTPS,streaming 上传与下载,配置超时时间,IPv6, ...
- Android HttpURLConnection And HttpClient
Google的工程师的一个博客写到: HttpURLConnection和HttpClient Volley HTTP请求时:在Android 2.3及以上版本,使用的是HttpURLConnecti ...
- 转-Android联网 — HttpURLConnection和HttpClient选择哪个好?
http://www.ituring.com.cn/article/199619?utm_source=tuicool 在Android开发中,访问网络我们是选择HttpURLConnection还是 ...
- [转]Android访问网络,使用HttpURLConnection还是HttpClient
转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/12452307 最近在研究Volley框架的源码,发现它在HTTP请求的使用上比较有 ...
- HttpURLConnection与HttpClient浅析
转自:https://blog.csdn.net/u012838207/article/details/82867701 HttpURLConnection与HttpClient浅析 1. GET请求 ...
- HttpURLConnection与HttpClient随笔
目前在工作中遇到的需要各种对接接口的工作,需要用到HTTP的知识,工作完成后想要做一些笔记,本来知识打算把自己写的代码粘贴上来就好了,但是偶然发现一篇博文对这些知识的总结非常到位,自认无法写的这么好, ...
- HttpURLConnection与HttpClient浅析---转
HttpURLConnection与HttpClient浅析 1. GET请求与POST请求 HTTP协议是现在Internet上使用得最多.最重要的协议了,越来越多的Java应用程序需要直接通过HT ...
随机推荐
- Selenium Books
Recently, some of my projects rely heavily upon tests with selenium. Some books about selenium are c ...
- CCF计算机职业资格认证考试题解
CCF计算机职业资格认证考试题解系列文章为meelo原创,请务必以链接形式注明本文地址 CCF计算机职业资格认证考试题解 CCF计算机软件能力认证(简称CCF CSP认证)是CCF计算机职业资格认证系 ...
- NET定时任务组件Hangfire
开源的.NET定时任务组件Hangfire解析 项目慢慢就要开工了,很多园友都在问这个事情,看来大伙对这事很上心啊,事情需要一步步的来,尽量写出一个我们都满意的项目.以前每次在博客前面都会扯淡一下,不 ...
- SpringBoot的搭建
一:搭建 1.环境要求 Java7及以上 Spring Framework4.1.5及以上 2.新建一个maven工程 3.pom.xml(生成) <!-- 必须引入spring-parent, ...
- 004.RAID删除
一 卸载RAID [root@kauai ~]# umount /dev/md0 #卸载挂载点 二 停止RAID设备 [root@kauai ~]# mdadm -S /dev/md0 #停用RAID ...
- ApiPost自动化测试基础之:如何使用测试校验(测试用例)?
我们在<ApiPost的环境变量的定义和使用>和<ApiPost自动化测试基础之:接口参数依赖的情景处理>分别讲解了ApiPost环境变量的定义.使用以及基于环境变量的接口参数 ...
- 设计模式-装饰者模式(Decorator Pattern)
本文由@呆代待殆原创,转载请注明出处. 此设计模式遵循的设计原则之一:类应该支持扩展,而拒绝修改(Open-Closed Principle) 装饰者模式简述 装饰者模式通过组合的方式扩展对象的特性, ...
- QT学习笔记9:QTableWidget的用法总结
最近用QT中表格用的比较多,使用的是QTableWidget这个控件,总结一下QTableWidget的一些相关函数. 1.将表格变为禁止编辑: tableWidget->setEditTrig ...
- BZOJ1171 : 大sz的游戏
f[i]=min(f[j])+1,线段j与线段i有交,且l[i]-l[j]<=L. 线段j与线段i有交等价于y[j]>=x[i],x[j]<=y[i]. 因为l[i]递增,所以可以维 ...
- BZOJ4115 : [Wf2015]Tile Cutting
设一种方案里三角形上三个点的坐标分别为$(0,0),(-a,b),(c,d)$,则得到的平行四边形的面积为$ac+bd$. 设$d(n)$为$n$的约数个数,$D$为$d$的生成函数,则答案的生成函数 ...