JAVA中使用Apache HttpComponents Client的进行GET/POST请求使用案例
一、简述需求
平时我们需要在JAVA中进行GET、POST、PUT、DELETE等请求时,使用第三方jar包会比较简单。常用的工具包有:
1、https://github.com/kevinsawicki/http-request (对应Maven包:http://mvnrepository.com/artifact/com.github.kevinsawicki/http-request)
2、http://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient/4.5.5
第1个包使用起来比较简单,如下:
package songxingzhu.utils.request;
import com.github.kevinsawicki.http.HttpRequest;
public class RequestUtils {
private static final String defaultCharset = "utf-8";
private static final int connectTimeoutInMissecond = 10000;
private static final int readTimeoutInMissecond = 30000;
public static RequestResult getJsonText(String url, String charset) {
if (charset == null) charset = defaultCharset;
HttpRequest request = HttpRequest.get(url).connectTimeout(connectTimeoutInMissecond).readTimeout(readTimeoutInMissecond);
String body = request.body(charset);
int code = request.code();
request.disconnect();
return new RequestResult(body, code);
}
}
本文主要讲第2个包的使用。
二、开发过程
如下图所示:
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test; import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List; public class HttpClientTest {
@Test
public void get() throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet request = new HttpGet("https://xingzhu-song.chinacloudsites.cn/kvMapping?orgId=b11647e8-0e36-44fd-84fa-262c4fcfbe43");
request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0");
CloseableHttpResponse response = httpClient.execute(request);
HttpEntity entry = response.getEntity();
int code = response.getStatusLine().getStatusCode();
System.out.println("\tcode:" + code);
String result = EntityUtils.toString(entry);
System.out.println("\tresult:" + result);
HttpClientUtils.closeQuietly(response);
HttpClientUtils.closeQuietly(httpClient);
} @Test
public void postForm() throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost request = new HttpPost("https://xingzhu-song.chinacloudsites.cn/monitoring/metric/definitions");
List<NameValuePair> list = new ArrayList<>();
list.add(new BasicNameValuePair("orgId", "b11647e8-0e36-44fd-84fa-262c4fcfbe43"));
list.add(new BasicNameValuePair("instanceId", "1b0acfbb-d7f2-4f0d-a026-734c686ee4ba"));
request.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
CloseableHttpResponse response = httpClient.execute(request);
HttpEntity entry = response.getEntity();
int code = response.getStatusLine().getStatusCode();
System.out.println("\tcode:" + code);
String result = EntityUtils.toString(entry);
System.out.println("\tresult:" + result);
HttpClientUtils.closeQuietly(response);
HttpClientUtils.closeQuietly(httpClient);
} @Test
public void postJSON() throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost request = new HttpPost("https://xingzhu-song.chinacloudsites.cn/kvMapping/valid?orgId=b11647e8-0e36-44fd-84fa-262c4fcfbe43");
String body = "{" +
" \"serviceId\": \"pip\",\n" +
" \"key\": \"pipDnsLabel\",\n" +
" \"value\": \"abcdefg\",\n" +
" \"dependenceOn\": {\"pipLocation\":\"chinanorth\"}\n" +
"}";
request.setEntity(new StringEntity(body, "UTF-8"));
request.setHeader("content-type", "application/json");
CloseableHttpResponse response = httpClient.execute(request);
HttpEntity entry = response.getEntity();
int code = response.getStatusLine().getStatusCode();
System.out.println("\tcode:" + code);
String result = EntityUtils.toString(entry);
System.out.println("\tresult:" + result);
HttpClientUtils.closeQuietly(response);
HttpClientUtils.closeQuietly(httpClient);
} @Test
public void testUrl() throws URISyntaxException {
URIBuilder uriBuilder = new URIBuilder("https://xingzhu-song.chinacloudsites.cn");
uriBuilder.setPath("kvMapping");
uriBuilder.setCharset(Charset.forName("UTF-8"));
uriBuilder.setParameter("key1", "value1");
uriBuilder.setParameter("key2", "value2");
//uriBuilder.setUserInfo("username","password"); //https://username:password@xingzhu-song.chinacloudsites.cn/kvMapping?key1=value1&key2=value2
URI uri = uriBuilder.build();
System.out.println(uri);//https://xingzhu-song.chinacloudsites.cn/kvMapping?key1=value1&key2=value2
}
}
JAVA中使用Apache HttpComponents Client的进行GET/POST请求使用案例的更多相关文章
- Apache HttpComponents Client 4.0快速入门/升级-2.POST方法访问网页
Apache HttpComponents Client 4.0已经发布多时,httpclient项目从commons子项目挪到了HttpComponents子项目下,httpclient3.1和 h ...
- Java中apache下面FtpClient主动模式和被动模式
最近在做ftp文件上传的时候,开发测试环境上传都没有问题,但是在开发环境缺无法上传,但是也没有报错,纠结了老久.最后看到网上有说FtpClient有主动模式和被动模式之分,然后就解决了. FTPCli ...
- spring .cloud ------------java.lang.RuntimeException: com.netflix.client.ClientException,Caused by: java.lang.IllegalArgumentException: MIME type may not contain reserved characters
1.问题的发生 Feign在默认情况下使用的是JDK原生的URLConnection发送HTTP请求,没有连接池,但是对每个地址会保持一个长连接,即利用HTTP的persistence connect ...
- org.apache.http.client.HttpClient使用方法
一.org.apache.commons.httpclient和org.apache.http.client区别(转) 官网说明: http://hc.apache.org/httpclient- ...
- org.apache.commons.httpclient和org.apache.http.client区别(转)
官网说明: http://hc.apache.org/httpclient-3.x/ Commons HttpClient项目现已结束,不再开发.它已被其HttpClient和HttpCore模块中的 ...
- java.lang.NoClassDefFoundError: org/apache/http/client/config/RequestConfig
java 错误.java.lang.NoClassDefFoundError: org/apache/http/client/config/RequestConfig 本质上是httpClient的j ...
- Apache HttpComponents中的cookie匹配策略
Apache HttpComponents中的cookie匹配策略 */--> pre.src {background-color: #292b2e; color: #b2b2b2;} pre. ...
- apache.http.client.HttpClient
前言 HTTP 协议可能是现在 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源.虽然在 JDK 的 java net包中已经提 ...
- Java:HttpClient篇,HttpClient4.2在Java中的几则应用:Get、Post参数、Session(会话)保持、Proxy(代理服务器)设置,多线程设置...
新版HttpClient4.2与之前的3.x版本有了很大变化,建议从http://hc.apache.org/处以得到最新的信息. 关于HttpCore与HttpClient:HttpCore是位于H ...
随机推荐
- 《UNIX环境高级编程(第3版)》
<UNIX环境高级编程(第3版)> 基本信息 原书名:Advanced Programming in the UNIX Environment (3rd Edition) (Addison ...
- HTML5 本地文件操作之FileSystemAPI整理(二)
一.文件目录操作 1.DirectoryEntry对象 属性: 1.isFile: 操作对象的是否为文件,DirectoryEntry对象固定其值为false 2.isDirectory: 操作对象是 ...
- HTML5 本地文件操作之FileSystemAPI简介
一.FileSystemAPI简介 HTML5的文件操作Api中 1.FileAPI,用于基础的客户端本地文件读取,目前大多数接口已经被主流浏览器支持,点击查看更多参考 2.FileSystemAPI ...
- RSA加密解密及RSA签名和验证及证书
RSA加密解密及RSA签名和验证及证书 公钥是给别人的 发送密文使用公钥加密 验证签名使用公钥验证 私钥是自己保留的 接受密文使用私钥解密 发送签名使用私钥签名 上述过程逆转是不行的,比如使用私钥加密 ...
- 用java打暴雪星际争霸(2)——执行測试机器人
原创内容.转载请注明. 在上一节安装完成后.或者您直接打开我分享的虚拟机后,我如今将解说怎样启动測试机器人. 第一步,打开Eclipse,导入机器人演示样例项目,如图所看到的. 第二步,我们能够看到就 ...
- scrapy框架系列 (4) Scrapy Shell
Scrapy Shell Scrapy终端是一个交互终端,我们可以在未启动spider的情况下尝试及调试代码,也可以用来测试XPath或CSS表达式,查看他们的工作方式,方便我们爬取的网页中提取的数据 ...
- CSS-图片不变形设置
不管网页做的美还是丑,有一个问题始终是无法躲避的,就是有的时候会遇到图片变形的问题,之前遇到过这种问题解决过,不过还是整体的重新研究了一下图片,其中主要涉及到的知识点就是max-width和max-h ...
- iOS开发-类簇(Class Cluster)
类簇(Class Cluster)是定义相同的接口并提供相同功能的一组类的集合,仅公开接口的抽象类也可以称之为类簇的公共类,每个具体类的接口有公共类的接口抽象化,并隐藏在簇的内部.这些类一般不能够直 ...
- 用Visual C#来清空回收站(1)
视窗操作系统的回收站是对文件一种保护措施,他主要是作用是不言而喻的.在新的视窗2000系统之中,当我把文件删除到回收站中以后,按动"清空回收站"按钮,想清空回收站,此时往往提示&q ...
- android 数据加密——加密的概述
数据加密又称密码学,它是一门历史悠久的技术,指通过加密算法和加密密钥将明文转变为密文,而解密则是通过解密算法和解密密钥将密文恢复为明文.数据加密目前仍是计算机系统对信息进行保护的一种最可靠的办法.它利 ...