导出mven依赖

      <dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
package testhttpclient.testhttpclient;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set; import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
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.config.RequestConfig;
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.methods.HttpRequestBase;
import org.apache.http.impl.client.BasicCookieStore;
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; public class HttpClientComm { /**
* 客户端总成
*/
protected CloseableHttpClient httpclient;
/**
* cookie信息
*/
protected Set<String>cookies;
/**
* get方法
*/
protected HttpGet httpget;
/**
* post方法
*/
protected HttpPost httppost;
/**
* 代理
*/
protected HttpHost proxy;
/**
* 设置默认延迟时间
*/
protected RequestConfig requestconfig;
/**
* 返回存储数据map
*/
protected Map<String,String>resultmap; /**
* 响应状态
*/
public final String HTTPSTATUS="status";
/**
* 返回数据结果
*/
public final String HTTPRESULT="httpresult";
/**
* 初始化客户端
*/
public HttpClientComm() {
httpclient=HttpClients.createDefault();
requestconfig=RequestConfig.custom().setConnectionRequestTimeout(10*1000).setSocketTimeout(10*1000).build();
cookies=new HashSet<String>(16);
}
/**
* 初始化请求,设置请求时间
* @param millistimeout
*/
public HttpClientComm(int millistimeout) {
httpclient=HttpClients.createDefault();
requestconfig=RequestConfig.custom().setConnectionRequestTimeout(10*1000).setSocketTimeout(10*1000).build();
cookies=new HashSet<String>(16);
}
/**
* 设置代理
*
* @Data:上午11:02:43
* @Package:testhttpclient.testhttpclient
* @Return:void
* @Auth:diao
*/
public void setProxy(String Address,int port)
{
proxy=new HttpHost(Address, port);
requestconfig=RequestConfig.custom().setProxy(proxy).build();
}
/**
* 释放请求资源
*
* @Data:上午11:03:27
* @Package:testhttpclient.testhttpclient
* @Return:void
* @Auth:diao
*/
public void close()
{
if(cookies!=null)
{
cookies=null;
}
if(proxy!=null)
{
proxy=null;
}
if(resultmap!=null)
{
resultmap=null;
}
if(httpget!=null)
{
httpget.releaseConnection();
}
if(httppost!=null)
{
httppost.releaseConnection();
}
if(httpclient!=null)
{
try {
httpclient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
httpclient=null;
}
}
}
/**
*
* get请求传递的连接,请求头
* @Data:上午11:15:10
* @Package:testhttpclient.testhttpclient
* @Return:Map<String,String>
* @Auth:diao
*/
public Map<String,String>get(String url,Map<String,String>headers){
httpget=new HttpGet(url);
httpget.setConfig(requestconfig);
headers.forEach((a,b)->{
httpget.addHeader(a, b);
});
httpget.addHeader("cookie",cookies.toString().substring(1,cookies.toString().length()-1)); CloseableHttpResponse respose=null; try {
respose=httpclient.execute(httpget);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return getResData(respose, httpget);
}
/**
* post请求方式
*
* @Data:下午2:01:15
* @Package:testhttpclient.testhttpclient
* @Return:Map<String,String>
* @Auth:diao
*/
public Map<String,String>post(String url,Map<String,String>headers,Map<String,String>params,String charset) throws UnsupportedEncodingException
{
//设置请求方法及连接信息
httppost=new HttpPost(url);
//设置请求参数
httppost.setConfig(requestconfig);
//设置请求头
headers.forEach((a,b)->{
httpget.addHeader(a, b);
});
BasicCookieStore cookie=new BasicCookieStore();
HttpClients.custom().setDefaultCookieStore(cookie).build();
httppost.addHeader("cookie",cookies.toString().substring(1,cookies.toString().length()-1));
List<NameValuePair>pairs=null;
if(params!=null&&!params.isEmpty())
{
pairs=new ArrayList<NameValuePair>(params.size());
for(String key:params.keySet())
{
pairs.add(new BasicNameValuePair(key,params.get(key).toString()));
}
}
if(pairs!=null&&pairs.size()>0)
{
httppost.setEntity(new UrlEncodedFormEntity(pairs,charset));
}
//执行请求
HttpResponse response=null;
try {
response=httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return getResData(response, httppost);
} /**
* 处理http结果请求
*
* @Data:下午1:42:28
* @Package:testhttpclient.testhttpclient
* @Return:Map<String,String>
* @Auth:diao
*/
public Map<String,String> getResData(HttpResponse response,HttpRequestBase requestbase)
{
int status=405;
if(response!=null)
{
status=response.getStatusLine().getStatusCode();
for(Header header:response.getAllHeaders())
{
if("Set-Cookie".equalsIgnoreCase(header.getName()))
{
cookies.add(header.getValue());
}
}
}
resultmap=new HashMap<>(16);
resultmap.put(HTTPRESULT,status+"");
resultmap.put(HTTPRESULT, null);
if(status!=HttpStatusEnum.OK.code())
{
requestbase.abort();
}else {
HttpEntity entity= response.getEntity();
if(entity!=null)
{
try {
String data=EntityUtils.toString(entity,"utf-8"); String start="[",end="]";
if(data.startsWith(start))
{
data=data.substring(1);
}
if(data.endsWith(end))
{
data=data.substring(0,data.length()-1);
}
data=data.replaceAll("\\\\t|\\\\n|\\r\\n","");
data=data.replaceAll("\\\\/","/");
data=decodeUnicode(data);
resultmap.put(HTTPRESULT, data);
//关闭流
EntityUtils.consume(entity);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response=null;
}
}
return resultmap;
}
/**
* unicode转中文
*
* @Data:下午1:44:16
* @Package:testhttpclient.testhttpclient
* @Return:String
* @Auth:diao
*/
public static String decodeUnicode(final String dataStr) {
int start = 0;
int end = 0;
final StringBuffer buffer = new StringBuffer();
while (start > -1) {
end = dataStr.indexOf("\\u", start + 2);
String charStr = "";
if (end == -1) {
charStr = dataStr.substring(start + 2, dataStr.length());
} else {
charStr = dataStr.substring(start + 2, end);
}
// 16进制parse整形字符串。
char letter = (char) Integer.parseInt(charStr, 16);
buffer.append(new Character(letter).toString());
start = end;
}
return buffer.toString();
}
/**
* 获取请求头
*
* @Data:下午1:44:16
* @Package:testhttpclient.testhttpclient
* @Return:String
* @Auth:diao
*/
public Map<String,String>getCommHeader(){
Map<String,String>headers=new HashMap<String, String>(16);
headers.put("User-Agent","Mozilla/5.0(Window NT 6.1; WOW64; rv:58.0) Gecko/20100101 Firfox/58.0");
headers.put("Accept","application/json,text/plain,*/*");
headers.put("Accept-Language","zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
headers.put("Accept-Encoding","gzip,deflate");
headers.put("Connection","keep-alive");
return headers;
} public void test(String ip,int port,String jobid)
{
String url=String.format("http://%s:%d/jobs/%s/yarn-cancel",ip,port,jobid);
HttpClientComm httpclient=new HttpClientComm();
Map<String,String>header=new HashMap<String, String>(16);
header.put("Host",ip+":"+port);
header.put("Referer","http://"+ip+":"+port);
Map<String,String>Resultmap=httpclient.get(url, header);
String httpstatus=Resultmap.get(httpclient.HTTPSTATUS);
String resultmap=Resultmap.get(httpclient.HTTPRESULT);
if(httpstatus.isEmpty()&&HttpStatusEnum.ACCEPTED.code()==Integer.parseInt(httpstatus))
{
//json解析 }
} }

所有状态枚举类

package testhttpclient.testhttpclient;

/**
*
* @author sdzw
*
*/
public enum HttpStatusEnum {
/**
* 请继续发送请求的剩余部分
*/
CONTINUE(100, "Continue", "请继续发送请求的剩余部分"), SWITCHING_PROTOCOLS(101, "Switching Protocols", "协议切换"), PROCESSING(102, "Processing", "请求将继续执行"), // for 103 https://news.ycombinator.com/item?id=15590049
CHECKPOINT(103, "Checkpoint", "可以预加载"), OK(200, "OK", "请求已经成功处理"), CREATED(201, "Created", "请求已经成功处理,并创建了资源"), ACCEPTED(202, "Accepted", "请求已经接受,等待执行"), NON_AUTHORITATIVE_INFORMATION(203, "Non-Authoritative Information", "请求已经成功处理,但是信息不是原始的"), NO_CONTENT(204, "No Content", "请求已经成功处理,没有内容需要返回"), RESET_CONTENT(205, "Reset Content", "请求已经成功处理,请重置视图"), PARTIAL_CONTENT(206, "Partial Content", "部分Get请求已经成功处理"), MULTI_STATUS(207, "Multi-Status", "请求已经成功处理,将返回XML消息体"), ALREADY_REPORTED(208, "Already Reported", "请求已经成功处理,一个DAV的绑定成员被前一个请求枚举,并且没有被再一次包括"), IM_USED(226, "IM Used", "请求已经成功处理,将响应一个或者多个实例"), MULTIPLE_CHOICES(300, "Multiple Choices", "提供可供选择的回馈"), MOVED_PERMANENTLY(301, "Moved Permanently", "请求的资源已经永久转移"), FOUND(302, "Found", "请重新发送请求"), // MOVED_TEMPORARILY(302, "Moved Temporarily", "") 已经过时
SEE_OTHER(303, "See Other", "请以Get方式请求另一个URI"), NOT_MODIFIED(304, "Not Modified", "资源未改变"), USE_PROXY(305, "Use Proxy", "请通过Location域中的代理进行访问"), // 306在新版本的规范中被弃用 TEMPORARY_REDIRECT(307, "Temporary Redirect", "请求的资源临时从不同的URI响应请求"),
RESUME_INCOMPLETE(308, "Resume Incomplete", "请求的资源已经永久转移"), BAD_REQUEST(400, "Bad Request", "请求错误,请修正请求"), UNAUTHORIZED(401, "Unauthorized", "没有被授权或者授权已经失效"), PAYMENT_REQUIRED(402, "Payment Required", "预留状态"), FORBIDDEN(403, "Forbidden", "请求被理解,但是拒绝执行"), NOT_FOUND(404, "Not Found", "资源未找到"), METHOD_NOT_ALLOWED(405, "Method Not Allowed", "请求方法不允许被执行"), NOT_ACCEPTABLE(406, "Not Acceptable", "请求的资源不满足请求者要求"), PROXY_AUTHENTICATION_REQUIRED(407, "Proxy Authentication Required", "请通过代理进行身份验证"), REQUEST_TIMEOUT(408, "Request Timeout", "请求超时"), CONFLICT(409, "Conflict", "请求冲突"), GONE(410, "Gone", "请求的资源不可用"), LENGTH_REQUIRED(411, "Length Required", "Content-Length未定义"), PRECONDITION_FAILED(412, "Precondition Failed", "不满足请求的先决条件"), REQUEST_ENTITY_TOO_LARGE(413, "Request Entity Too Large", "请求发送的实体太大"), REQUEST_URI_TOO_LONG(414, "Request-URI Too Long", "请求的URI超长"), UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type", "请求发送的实体类型不受支持"), REQUESTED_RANGE_NOT_SATISFIABLE(416, "Requested range not satisfiable", "Range指定的范围与当前资源可用范围不一致"), EXPECTATION_FAILED(417, "Expectation Failed", "请求头Expect中指定的预期内容无法被服务器满足"), LOCKED(423, "Locked", "当前资源被锁定"), FAILED_DEPENDENCY(424, "Failed Dependency", "由于之前的请求发生错误,导致当前请求失败"), UPGRADE_REQUIRED(426, "Upgrade Required", "客户端需要切换到TLS1.0"), PRECONDITION_REQUIRED(428, "Precondition Required", "请求需要提供前置条件"), TOO_MANY_REQUESTS(429, "Too Many Requests", "请求过多"), REQUEST_HEADER_FIELDS_TOO_LARGE(431, "Request Header Fields Too Large", "请求头超大,拒绝请求"), INTERNAL_SERVER_ERROR(500, "Internal Server Error", "服务器内部错误"), NOT_IMPLEMENTED(501, "Not Implemented", "服务器不支持当前请求的部分功能"), BAD_GATEWAY(502, "Bad Gateway", "响应无效"), SERVICE_UNAVAILABLE(503, "Service Unavailable", "服务器维护或者过载,拒绝服务"), GATEWAY_TIMEOUT(504, "Gateway Timeout", "上游服务器超时"), HTTP_VERSION_NOT_SUPPORTED(505, "HTTP Version not supported", "不支持的HTTP版本"), VARIANT_ALSO_NEGOTIATES(506, "Variant Also Negotiates", "服务器内部配置错误"), INSUFFICIENT_STORAGE(507, "Insufficient Storage", "服务器无法完成存储请求所需的内容"), LOOP_DETECTED(508, "Loop Detected", "服务器处理请求时发现死循环"), BANDWIDTH_LIMIT_EXCEEDED(509, "Bandwidth Limit Exceeded", "服务器达到带宽限制"), NOT_EXTENDED(510, "Not Extended", "获取资源所需的策略没有被满足"), NETWORK_AUTHENTICATION_REQUIRED(511, "Network Authentication Required", "需要进行网络授权");
/**
* 状态码
*/
private final int code;
/**
* 中文含义
*/
private final String reasonPhraseUS;
/**
* 英文含义
*/
private final String reasonPhraseCN;
/**
* 某个数字代表的错误类型
*/
private static final int
INFORMATIONAL = 1,
SUCCESSFUL = 2,
REDIRECTION = 3,
CLIENT_ERROR = 4,
SERVER_ERROR = 5; HttpStatusEnum(int code, String reasonPhraseUS, String reasonPhraseCN)
{
this.code = code;
this.reasonPhraseUS = reasonPhraseUS;
this.reasonPhraseCN = reasonPhraseCN;
}
public int code()
{
return code; }
public String reasonPhraseUS()
{
return reasonPhraseUS; }
public String reasonPhraseCN() { return reasonPhraseCN; }
public static HttpStatusEnum valueOf(int code) {
for (HttpStatusEnum httpStatus : values()) {
if (httpStatus.code() == code) {
return httpStatus;
}
} throw new IllegalArgumentException("No matching constant for [" + code + "]"); } public boolean is1xxInformational()
{
return type() == INFORMATIONAL; }
public boolean is2xxSuccessful()
{
return type() == SUCCESSFUL; }
public boolean is3xxRedirection()
{
return type() == REDIRECTION; }
public boolean is4xxClientError()
{
return type() == CLIENT_ERROR; }
public boolean is5xxServerError()
{
return type() == SERVER_ERROR; }
private int type()
{
return (int) code / 100; } }

httpclient实现的get请求及post请求的更多相关文章

  1. JAVA发送HttpClient请求及接收请求结果

    1.写一个HttpRequestUtils工具类,包括post请求和get请求 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 2 ...

  2. java使用httpclient封装post请求和get的请求

    在我们程序员生涯中,经常要复用代码,所以我们应该养成时常整理代码的好习惯,以下是我之前封装的httpclient的post和get请求所用的代码: package com.marco.common; ...

  3. 如何使用HttpClient来发送带客户端证书的请求,以及如何忽略掉对服务器端证书的校验

    最近要做客户端和服务器端的双向认证,在客户端向服务器端发送带证书的请求这里有一点问题,网上的例子大多都不太好使,于是找了github上httpclient源代码中的例子改造了一下,终于弄明白了 git ...

  4. JAVA发送HttpClient请求及接收请求结果过程

    1.写一个HttpRequestUtils工具类,包括post请求和get请求 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 ...

  5. httpclient开启代理,获取java中请求的url

    背景:在httpclent做post或者get请求时,请求返回的数据总是和预想的不一致,但是有不知道怎么排查问题,经同事说httpclient可以设置代理,就可以获取请求前数据的一些问题,帮助我排查问 ...

  6. 封装HttpClient进行http请求与https请求

    一.https忽略证书 /** * 用于进行Https请求的HttpClient * * @author joey * */ public class SSLClient { public stati ...

  7. httpClient Post例子,Http 四种请求访问代码 HttpGet HttpPost HttpPut HttpDelete

    httpclient post方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 //----1. HttpPost request = new HttpPost(ur ...

  8. httpclient连接池在ES Restful API请求中的应用

    package com.wm.utils; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http ...

  9. 在ASP.NET Core中用HttpClient(三)——发送HTTP PATCH请求

    在前面的两篇文章中,我们讨论了很多关于使用HttpClient进行CRUD操作的基础知识.如果你已经读过它们,你就知道如何使用HttpClient从API中获取数据,并使用HttpClient发送PO ...

随机推荐

  1. Hibernate session中的createCriteria方法

    在应用中获取session对象: Session session=  HibernateUtil.getSession(); List list=session.createCriteria(Mete ...

  2. 使用Java打印字符串表格(中英文内容不乱)

    最近在学习使用java来编写cli应用,但是在信息展示上碰到了难题.原因是没有很好工具来展示一个由字符串组成的表格.在git上搜到阿里巴巴有一个叫做 text-ui 的开源项目可以用,但是这个工具在制 ...

  3. 【Spring】20、使用TransactionSynchronizationManager在spring事务提交之后进行一些操作。

    本文内容 如何在spring事务提交之后进行一些操作,这些操作必须得在该事务成功提交后才执行,回滚则不执行. 要点 如何在spring事务提交之后操作 如何在spring事务回滚之后操作 实现方案 使 ...

  4. 【Dubbo&&Zookeeper】2、 windows平台dubbo-admin管理平台搭建

    一.前言 dubbo的使用,其实只需要有注册中心,消费者,提供者这三个就可以使用了,但是并不能看到有哪些消费者和提供者,为了更好的调试,发现问题,解决问题,因此引入dubbo-admin.通过dubb ...

  5. tortoisegit安装

    1.下载tortoisegit:https://tortoisegit.org/download/ 2.下载git 64位 3. 双击开始安装,选择默认,点击下一步 4.接着是选择安装目录,可以保持默 ...

  6. Tomcat 8默认工具manager管理页面访问配置

    Tomcat 8默认工具manager管理页面访问配置 1. 分配相关的角色权限 需要配置的配置文件是${catalina.home}/conf/tomcat-users.xml先给Tomcat访问相 ...

  7. 自定义控件详解(四):Paint 画笔路径效果

    Paint  画笔 ,即用来绘制图形的"笔" 前面我们知道了Paint的一些基本用法: paint.setAntiAlias(true);//抗锯齿功能 paint.setColo ...

  8. 【第二篇】SAP ABAP7.5x新语法之OPEN SQL

    公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:SAP ABAP7.5x系列之OPEN SQL ...

  9. 在LINUX上部署SOFA

    JDK1.6环境变量 vim /etc/profile JAVA_HOME=/usr/local/java/jdk1.6.0_45PATH=$JAVA_HOME/bin:$PATHCLASSPATH= ...

  10. Python 列表(List)包含的函数与方法

    Python列表函数&方法 Python包含以下函数: 序号 函数 1 cmp(list1, list2)比较两个列表的元素 2 len(list)列表元素个数 3 max(list)返回列表 ...