HttpClient 学习笔记--源自技术
2016-04-06 16:23
465 查看
HttpClient 是 Apache提供的一个HTTP连接工具包
网址:http://hc.apache.org/
4.5jar包下载:httpclient 4.5
4.5src包下载:httpclient 4.5-src
[java] view
plain copy
/*基本的get请求*/
public final static void basicGet() throws ClientProtocolException, IOException{
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpget = new HttpGet("http://www.weather.com.cn/data/sk/101010100.html");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
StatusLine statusLine = response.getStatusLine();
System.out.println(statusLine);
HttpEntity resEntity = response.getEntity();
InputStream content = resEntity.getContent();
InputStreamReader reader = new InputStreamReader(content);
BufferedReader bufferedReader = new BufferedReader(reader);
String lineTxt = null;
while((lineTxt = bufferedReader.readLine()) != null){
System.out.println(lineTxt);
}
//调用中止请求对象
httpget.abort();
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
/*基本的Post请求*/
public final static void basicPost() throws ClientProtocolException, IOException{
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("http://www.apache.org/");
CloseableHttpResponse response = httpclient.execute(httppost);
try {
StatusLine statusLine = response.getStatusLine();
System.out.println(statusLine);
HttpEntity resEntity = response.getEntity();
InputStream content = resEntity.getContent();
InputStreamReader reader = new InputStreamReader(content);
BufferedReader bufferedReader = new BufferedReader(reader);
String lineTxt = null;
while((lineTxt = bufferedReader.readLine()) != null){
System.out.println(lineTxt);
}
//调用中止请求对象
httppost.abort();
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
/*带参数的Post请求*/
public final static void parameterPost() throws IOException{
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost("http://www.imooc.com/user/login");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("username", "u"));
nvps.add(new BasicNameValuePair("password", "p"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
System.out.println(response.getStatusLine());
System.out.println("Response content: " + EntityUtils.toString(response.getEntity(), "UTF-8"));
//调用中止请求对象
httpPost.abort();
}finally{
response.close();
}
}finally{
httpClient.close();
}
}
/* 上传文件
* 示例:ClientMultipartFormPost.java
* */
public final static void upload() throws IOException{
CloseableHttpClient httpClient = HttpClients.createDefault();
try{
HttpPost httpPost = new HttpPost("http://image.baidu.com/pictureup/uploadshitu?fr=flash&fm=index&pos=upload");
FileBody bin = new FileBody(new File("C:\\Users\\Administrator\\Downloads\\123.png"));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("fileName", bin).addPart("comment", comment).build();
httpPost.setEntity(reqEntity);
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println(response.getStatusLine());
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
} finally{
response.close();
}
}finally{
httpClient.close();
}
}
/* SSL
* 示例:ClientCustomSSL.java
* */
public final static void ssl() throws Exception {
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom()
.loadTrustMaterial(new File("my.keystore"), "nopassword".toCharArray(),
new TrustSelfSignedStrategy())
.build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
new String[] { "TLSv1" },
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.build();
try {
HttpGet httpget = new HttpGet("https://localhost/");
System.out.println("executing request " + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
EntityUtils.consume(entity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
/* HTTP上下文
* 示例:ClientCustomContext.java
**/
public final static void context() throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
// 创建一个cookie存储的实例
CookieStore cookieStore = new BasicCookieStore();
// 创建本地HTTP上下文
HttpClientContext localContext = HttpClientContext.create();
// 绑定定义cookie存储到上下文
localContext.setCookieStore(cookieStore);
HttpGet httpget = new HttpGet("http://www.baidu.com/");
// 将上下文作为参数
CloseableHttpResponse response = httpclient.execute(httpget, localContext);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
List<Cookie> cookies = cookieStore.getCookies();
for (int i = 0; i < cookies.size(); i++) {
System.out.println("Local cookie: " + cookies.get(i));
}
EntityUtils.consume(response.getEntity());
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
推荐博文
博文1
博文2
网址:http://hc.apache.org/
4.5jar包下载:httpclient 4.5
4.5src包下载:httpclient 4.5-src
[java] view
plain copy
/*基本的get请求*/
public final static void basicGet() throws ClientProtocolException, IOException{
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpget = new HttpGet("http://www.weather.com.cn/data/sk/101010100.html");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
StatusLine statusLine = response.getStatusLine();
System.out.println(statusLine);
HttpEntity resEntity = response.getEntity();
InputStream content = resEntity.getContent();
InputStreamReader reader = new InputStreamReader(content);
BufferedReader bufferedReader = new BufferedReader(reader);
String lineTxt = null;
while((lineTxt = bufferedReader.readLine()) != null){
System.out.println(lineTxt);
}
//调用中止请求对象
httpget.abort();
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
/*基本的Post请求*/
public final static void basicPost() throws ClientProtocolException, IOException{
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("http://www.apache.org/");
CloseableHttpResponse response = httpclient.execute(httppost);
try {
StatusLine statusLine = response.getStatusLine();
System.out.println(statusLine);
HttpEntity resEntity = response.getEntity();
InputStream content = resEntity.getContent();
InputStreamReader reader = new InputStreamReader(content);
BufferedReader bufferedReader = new BufferedReader(reader);
String lineTxt = null;
while((lineTxt = bufferedReader.readLine()) != null){
System.out.println(lineTxt);
}
//调用中止请求对象
httppost.abort();
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
/*带参数的Post请求*/
public final static void parameterPost() throws IOException{
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost("http://www.imooc.com/user/login");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("username", "u"));
nvps.add(new BasicNameValuePair("password", "p"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
System.out.println(response.getStatusLine());
System.out.println("Response content: " + EntityUtils.toString(response.getEntity(), "UTF-8"));
//调用中止请求对象
httpPost.abort();
}finally{
response.close();
}
}finally{
httpClient.close();
}
}
/* 上传文件
* 示例:ClientMultipartFormPost.java
* */
public final static void upload() throws IOException{
CloseableHttpClient httpClient = HttpClients.createDefault();
try{
HttpPost httpPost = new HttpPost("http://image.baidu.com/pictureup/uploadshitu?fr=flash&fm=index&pos=upload");
FileBody bin = new FileBody(new File("C:\\Users\\Administrator\\Downloads\\123.png"));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("fileName", bin).addPart("comment", comment).build();
httpPost.setEntity(reqEntity);
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println(response.getStatusLine());
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
} finally{
response.close();
}
}finally{
httpClient.close();
}
}
/* SSL
* 示例:ClientCustomSSL.java
* */
public final static void ssl() throws Exception {
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom()
.loadTrustMaterial(new File("my.keystore"), "nopassword".toCharArray(),
new TrustSelfSignedStrategy())
.build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
new String[] { "TLSv1" },
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.build();
try {
HttpGet httpget = new HttpGet("https://localhost/");
System.out.println("executing request " + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
EntityUtils.consume(entity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
/* HTTP上下文
* 示例:ClientCustomContext.java
**/
public final static void context() throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
// 创建一个cookie存储的实例
CookieStore cookieStore = new BasicCookieStore();
// 创建本地HTTP上下文
HttpClientContext localContext = HttpClientContext.create();
// 绑定定义cookie存储到上下文
localContext.setCookieStore(cookieStore);
HttpGet httpget = new HttpGet("http://www.baidu.com/");
// 将上下文作为参数
CloseableHttpResponse response = httpclient.execute(httpget, localContext);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
List<Cookie> cookies = cookieStore.getCookies();
for (int i = 0; i < cookies.size(); i++) {
System.out.println("Local cookie: " + cookies.get(i));
}
EntityUtils.consume(response.getEntity());
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
推荐博文
博文1
博文2
相关文章推荐
- 笔试笔记2 SNMP为应用层协议 UDP 计算机网络拓扑结构 静态路由 缺省路由 组播 VOIP
- 通过win7中cmd命令提示符telnet模拟http请求
- SpringMVC源码剖析(五)-消息转换器HttpMessageConverter
- 浅谈浏览器http的缓存机制
- Caffe学习系列(18): 绘制网络模型
- HTTP状态代码以及定义(深度好文,赶紧收藏)
- gem install 出现Errno::ECONNRESET: Connection reset by peer - SSL_connect (https://api.rubygems.org
- MDN开发者网络
- ios AFNetworking 3.0 报错 : *** Assertion failure in -[AFHTTPRequestSerializer requestWithMethod:URLSt
- 【bzoj 3275】Number(最小割)
- HTTP协议的8种请求类型介绍
- [置顶] 用 Java 实现断点续传 (HTTP)
- HTTP 学习笔记(4)----CGI
- OkHttp使用教程
- web服务器(jetty)处理请求出现NoSuchMethodError: javax.servlet.http.HttpServletResponse.getStatus()I
- Nesty 高性能轻量级Http Restful Server
- 网络抓包
- 在html中写python代码的语法和特点-----基于webpy的http服务器
- $_SERVER中的HTTP_HOST和SERVER_NAME的區別
- 网络请求为什么要使用第三方库???