HttpUtil

package com.eaju.util;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

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.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ByteArrayEntity;
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.springframework.http.HttpMethod;
public class HttpUtil {
public final static String APPLICATION_PROTOBUF = "application/x-protobuf;charset=UTF-8";
public final static String APPLICATION_JSON="application/json;charset=UTF-8";
public final static String APPLICATION_XML="application/xml;charset=UTF-8";
public final static String TEXT_PLAIN="text/plain;charset=UTF-8";

/**
*
* @param url
* @param params
* @param accept
* @return
* @throws IOException
*/
public static byte[] get(String url,Map<String,String> params,String accept) throws IOException{
CloseableHttpClient httpclient = HttpClients.createDefault();
if(params != null){
StringBuilder paramUrl = new StringBuilder();
for(String key:params.keySet()){
paramUrl.append(URLEncoder.encode(key,"UTF-8")).
append("=").
append(URLEncoder.encode(params.get(key),"UTF-8")).
append("&");
}
url+=url+"?"+paramUrl.substring(0,paramUrl.length()-1);
}
HttpGet httpGet =new HttpGet(url);
httpGet.setHeader("Accept", accept);
CloseableHttpResponse response =httpclient.execute(httpGet);
byte[] result = EntityUtils.toByteArray(response.getEntity());
response.close();
httpclient.close();
return result;

}

/**
*
* @param url
* @param accept
* @return
* @throws IOException
*/
public static byte[] get(String url,String accept) throws IOException{
return get(url,null,accept);
}

/**
*
* @param url
* @param params
* @param accept
* @return
* @throws IOException
*/
public static byte[] post(String url,Map<String,String> params,String accept)throws IOException{
return execute(url,HttpMethod.POST,params,accept);
}

/**
*
* @param url
* @param params
* @param accept
* @return
* @throws IOException
*/
public static byte[] patch(String url,Map<String,String> params,String accept)throws IOException{
return execute(url,HttpMethod.PATCH,params,accept);
}

/**
*
* @param url
* @param params
* @param accept
* @return
* @throws IOException
*/
public static byte[] put(String url,Map<String,String> params,String accept)throws IOException{
return execute(url,HttpMethod.PUT,params,accept);
}

/**
*
* @param url
* @param data
* @param contentType
* @param accept
* @return
* @throws IOException
*/
public static byte[] post(String url,byte [] data,String contentType,String accept)throws IOException{
return execute(url,HttpMethod.POST,data,contentType,accept);
}

/**
*
* @param url
* @param data
* @param contentType
* @param accept
* @return
* @throws IOException
*/
public static byte[] put(String url,byte [] data,String contentType,String accept)throws IOException{
return execute(url,HttpMethod.PUT,data,contentType,accept);
}

/**
*
* @param url
* @param data
* @param contentType
* @param accept
* @return
* @throws IOException
*/
public static byte[] patch(String url,byte [] data,String contentType,String accept)throws IOException{
return execute(url,HttpMethod.PATCH,data,contentType,accept);
}

/**
*
* @param url
* @param accept
* @return
* @throws IOException
*/
public static byte[] delete(String url,String accept)throws IOException{
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpDelete httpDelete = new HttpDelete(url);
httpDelete.setHeader("Accept", accept);
CloseableHttpResponse response =httpclient.execute(httpDelete);
byte[] result =EntityUtils.toByteArray(response.getEntity());
response.close();
httpclient.close();
return result;
}

/**
*
* @param url
* @param method
* @param params
* @param accept
* @return
* @throws IOException
*/
private static byte[] execute(String url,HttpMethod method,Map<String,String> params,String accept)throws IOException{
CloseableHttpClient httpclient = HttpClients.createDefault();
RequestBuilder requestBuilder;
switch (method){
case POST:
requestBuilder = RequestBuilder.post(url);
if(params != null){
List<NameValuePair> nvps = new ArrayList <NameValuePair>();
for(String key:params.keySet()){
nvps.add(new BasicNameValuePair(key, params.get(key)));
}
UrlEncodedFormEntity encodedFormEntity= new UrlEncodedFormEntity(nvps,Charset.forName("UTF-8"));
requestBuilder.setEntity(encodedFormEntity);
}
break;
case PUT:
if(params != null){
for(String key:params.keySet()){
url+="&"+URLEncoder.encode(key,"UTF-8")+"="+ URLEncoder.encode(params.get(key),"UTF-8");
}
url=url.replaceFirst("&","?");
}
System.out.println(url);
requestBuilder = RequestBuilder.put(url);
break;
case PATCH:
requestBuilder = RequestBuilder.patch(url);
requestBuilder.setHeader("Accept", accept);
requestBuilder.setCharset(Charset.forName("UTF-8"));
if(params != null){
for(String key:params.keySet()){
requestBuilder.addParameter(new BasicNameValuePair(key, params.get(key)));
}
}
break;
default:
requestBuilder = RequestBuilder.post(url);
if(params != null){
List<NameValuePair> nvps = new ArrayList <NameValuePair>();
for(String key:params.keySet()){
nvps.add(new BasicNameValuePair(key, params.get(key)));
}
UrlEncodedFormEntity encodedFormEntity= new UrlEncodedFormEntity(nvps,Charset.forName("UTF-8"));
requestBuilder.setEntity(encodedFormEntity);
}
break;
}

CloseableHttpResponse response =httpclient.execute(requestBuilder.build());
byte[] result =EntityUtils.toByteArray(response.getEntity());
response.close();
httpclient.close();
return result;
}

/**
*
* @param url
* @param method
* @param data
* @param contentType
* @param accept
* @return
* @throws IOException
*/
private static byte[] execute(String url,HttpMethod method,byte [] data,String contentType,String accept)throws IOException{
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpEntityEnclosingRequestBase httpRequest;
switch (method){
case POST:
httpRequest = new HttpPost(url);
break;
case PUT:
httpRequest = new HttpPut(url);
break;
case PATCH:
httpRequest = new HttpPatch(url);
break;
default:
httpRequest = new HttpPost(url);
}
httpRequest.setHeader("Content-Type", contentType);
httpRequest.setHeader("Accept", accept);
if(data != null){
httpRequest.setEntity(new ByteArrayEntity(data));
}
CloseableHttpResponse response =httpclient.execute(httpRequest);
byte[] result =EntityUtils.toByteArray(response.getEntity());
response.close();
httpclient.close();
return result;
}

}

时间: 2024-10-19 19:51:31

HttpUtil的相关文章

Android Xutils框架HttpUtil Get请求缓存问题

话说,今天和服务器开发人员小小的逗逼了一下,为啥呢? 话说今天有个"收藏产品"的请求接口,是get request的哦,我客户端写好接口后,点击"收藏按钮",返回"收藏成功",我又点了一下,尼玛居然还是"收藏成功",我再点一下,这下对了,返回给我"取消收藏成功",好吧,我又点了一下,彻底郁闷了,居然又是"取消收藏成功",这不是逗我的么? 于是我让服务器人员检查他的接口,是不是有啥幺蛾子,

自己写的Android端HttpUtil工具类

package com.sxt.jcjd.util; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Dictionary; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.

httputil用http获取请求的工具类

原文:httputil用http获取请求的工具类 源代码下载地址:http://www.zuidaima.com/share/1550463738612736.htm package com.zuidaima.xiaocan.demo.util; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Iterator; import java.util.

接口测试-自动化-Java实现-HttpUtil

HttpUtil负责提供Http的Post方法,其核心的方法如下: /** * Do POST request * @param url * @param parameterMap * @return * @throws Exception */ public String doPost(String url, Map<?, ?> parameterMap) throws Exception { /* Translate parameter map to parameter date stri

JavaUtil_07_HttpUtil_使用Hutool 封装的 HttpUtil

二.参考资料 1.[Hutool]Hutool工具类之Http工具——HttpUtil 原文地址:https://www.cnblogs.com/shirui/p/8423565.html

Apache HttpComponents 工具类 [ HttpUtil ]

pom.xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.5</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</gr

CookieUtil、EncryptUtil(各种加密算法)、HttpUtil

1.CookieUtil ublic class CookieUtil { // 默认缓存时间,单位/秒, 2H private static final int COOKIE_MAX_AGE = 60 * 60 * 2; // 保存路径,根路径 private static final String COOKIE_PATH = "/"; /** * 保存 * * @param response * @param key * @param value * @param ifRememb

微信JS-SDK实现上传图片功能

最近在项目开放中,有一个在微信WEB项目中上传图片的需求,一开始使用了传统的<input type="file">的方式去实现,但是后面发现在使用这种传统模式时会由于手机系统的差异而导致一系列的问题,后改用微信JSSDK的方式来实现. 总的来说,利用JSSDK来实现该功能一共分为四步. 1. 调用wx.config(),初始化jssdk的配置,并在jsApiList中配置上传图片需要的四个api('chooseImage','previewImage','uploadIma

Android附近基站+Wifi+IP+GPS多渠道定位方案

前言: 在移动客户端的开发中,地理位置定位是一个非常重要的环节,有些时候用户可能会限制web app或者Android app的一些权限,或者由于信号不佳的原因无法获得准确的GPS位置,甚至为了省电,用户可能对开启GPS开关可能会有抵触情绪.但是不能因为GPS的种种限制就放弃了对用户位置的追踪.要通过一切能发送出信号的物体尽可能准确的获取到用户的位置,有时可以牺牲一些精度,对于大数据和用户地区分布分析来说,有一个大体的位置已经够分析人员使用,而且绕开GPS的重重壁垒,为数据的完整性提供可靠方案