Fork me on GitEE

HttpUtils


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.HttpUriRequest;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URI;
import java.net.URLEncoder;
import java.util.*;

public class HttpUtils {
private static Logger log = LoggerFactory.getLogger(HttpUtils.class);
private static final String CHARSET_UTF8 = "UTF-8";


public static String formPost(String url, Map<String, String> map) throws Exception {
CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
httpClient = HttpClients.createDefault();
httpPost = new HttpPost(url);
//设置参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next();
list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
}
if (list.size() > 0) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, CHARSET_UTF8);
httpPost.setEntity(entity);
}
HttpResponse response = httpClient.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, CHARSET_UTF8);
}
}
return result;
}


public static String formGet(String findCompanyUrl, Map<String, String> map) throws Exception {

//创建一个httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建一个uri对象
URIBuilder uriBuilder = new URIBuilder(findCompanyUrl);

Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next();
uriBuilder.addParameter(elem.getKey(), elem.getValue());
}


HttpGet get = new HttpGet(uriBuilder.build());
get.setHeader("Accept", "application/json");
//执行请求
CloseableHttpResponse response = httpClient.execute(get);
//取响应的结果链接异常
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(statusCode);
HttpEntity entity = response.getEntity();
String string = EntityUtils.toString(entity, "utf-8");
System.out.println(string);
//关闭httpclient
response.close();
httpClient.close();

return string;
}


public static String post(String url, String reqBody, Map<String, String> headerInfo) throws UnsupportedEncodingException {
return post(url, reqBody, null, headerInfo);
}

public static String post(String url, String reqBody,
Map<String, String> params, Map<String, String> headerInfo) throws UnsupportedEncodingException {
DefaultHttpClient httpclient = new DefaultHttpClient();
String body = null;

HttpPost post = postForm(url, reqBody, params, headerInfo);

body = invoke(httpclient, post);

httpclient.getConnectionManager().shutdown();

return body;
}


public static String get(String url) {
DefaultHttpClient httpclient = new DefaultHttpClient();
String body = null;

HttpGet get = new HttpGet(url);
body = invoke(httpclient, get);

httpclient.getConnectionManager().shutdown();

return body;
}

private static String invoke(DefaultHttpClient httpclient,
HttpUriRequest httpost) {

HttpResponse response = sendRequest(httpclient, httpost);
String body = parseResponse(response);

return body;
}

private static String parseResponse(HttpResponse response) {
String result = null;
try {
if (null != response) {
HttpEntity entity = response.getEntity();
if (null != entity) {
result = EntityUtils.toString(entity, CHARSET_UTF8);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}

private static HttpResponse sendRequest(DefaultHttpClient httpclient,
HttpUriRequest httpost) {
HttpResponse response = null;

try {
response = httpclient.execute(httpost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}

private static HttpPost postForm(String url, String reqBody,
Map<String, String> params, Map<String, String> headerInfo) throws UnsupportedEncodingException {
HttpEntity httpEntity = null;
HttpPost httpost = null;
httpost = new HttpPost(url);
// jason 20151119 add s
if (headerInfo != null && headerInfo.size() > 0) {
Iterator<String> ite = headerInfo.keySet().iterator();
while (ite.hasNext()) {
String key = ite.next();
String headerVal = headerInfo.get(key);
httpost.setHeader(key, headerVal);
}
}
if (StringUtils.isNotBlank(reqBody)) {
httpEntity = new StringEntity(reqBody, HTTP.UTF_8);
((StringEntity) httpEntity).setContentEncoding("UTF-8");
((StringEntity) httpEntity).setContentType("application/json");
httpost.setEntity(httpEntity);
}
// jason 20151119 add e
if (null != params && params.size() > 0) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();

Set<String> keySet = params.keySet();
for (String key : keySet) {
nvps.add(new BasicNameValuePair(key, params.get(key)));
}

httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
}
return httpost;
}

/**
* 发送POST请求
*
* @param url
* @param params
* @return
* @throws UnsupportedEncodingException
*/
public static String sendPost(String url, String params) throws UnsupportedEncodingException {
String result = "";// 返回的结果
BufferedReader in = null;// 读取响应输入流
PrintWriter out = null;
try {
// 创建URL对象
java.net.URL connURL = new java.net.URL(url);
// 打开URL连接
java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL
.openConnection();
// 设置通用属性
httpConn.setRequestProperty("Content-type", "application/json;charset=utf-8");
// 设置POST方式
httpConn.setRequestMethod("POST");
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
httpConn.setConnectTimeout(3000);
// 获取HttpURLConnection对象对应的输出流
out = new PrintWriter(httpConn.getOutputStream());
// 发送请求参数
out.write(params);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应,设置编码方式
in = new BufferedReader(new InputStreamReader(
httpConn.getInputStream(), "utf-8"));
String line = "";
// 读取返回的内容
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
log.error("发送请求报错",e);
//result = "-1";
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
long b = System.currentTimeMillis();
return result;
}


/**
* 用于下载文件
* flag : 用于数据摆渡 , 输出流转换输入流 true为转换:::: 输出流转换输入流
* <p>
* 为false写到文件中
*/
public static Map<String, Object> doPostDownLoad(String url, Map params, OutputStream fos, boolean flag) {
BufferedReader in = null;
try {
// 定义HttpClient
HttpClient client = new DefaultHttpClient();
// 实例化HTTP方法
HttpPost request = new HttpPost();
request.setHeader("Content-Type", "*/*");
request.setURI(new URI(url));


//设置参数
request.setEntity(new StringEntity(JSONObject.toJSON(params).toString()));
HttpResponse response = client.execute(request);
int code = response.getStatusLine().getStatusCode();
if (code == 200) { //请求成功
Map<String, Object> mapResult = new HashMap<String, Object>();
mapResult.put("isSuccess", true);
if (flag) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
response.getEntity().writeTo(bos);
ByteArrayInputStream swapInputStream = new ByteArrayInputStream(bos.toByteArray());
mapResult.put("inputStream", swapInputStream);

} else {
response.getEntity().writeTo(fos);
}
return mapResult;
} else { //
System.out.println("状态码:" + code);
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}


/**
* @author:
* @Date: 2019-09-18 14:15
* @Description: 从流对象解析出字符串内容
*/
public static String getRespInputContent(String url) {

String str = "";
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response = null;
InputStream inputStream = null;
try {
response = client.execute(get);
inputStream = response.getEntity().getContent();

if (inputStream == null) {
return "";
}

StringBuilder sb = new StringBuilder();
String line;

BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
while ((line = br.readLine()) != null) {
sb.append(line);
}
str = sb.toString();
} catch (Exception e) {
System.out.println("返回报文获取失败 = "+e.getMessage());
return "返回报文获取失败";
}finally {
if(null != inputStream){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return str;
}





/**
* 表单提交参数和文件
* @param params
* @param file
* @return
*/
public static String postUploadFile(String urlPath, Map<String, String> params, File file) {

HttpPost httpPost = new HttpPost(urlPath);
CloseableHttpClient httpClient = HttpClients.createDefault();
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();

// 文件参数
entityBuilder.addPart("file", new FileBody(file, ContentType.create("multipart/form-data", "UTF-8")));
// 字符串参数
if (params != null && !params.isEmpty()) {
for (String key : params.keySet()) {
StringBody stringBody = new StringBody(params.get(key), ContentType.create("text/plain", "UTF-8"));
// <input type="text" name="userName" value="userName">
entityBuilder.addPart(key, stringBody);
}
}

try {
HttpEntity httpEntity = entityBuilder.build();
httpPost.setEntity(httpEntity);

RequestConfig config = RequestConfig.custom()
.setConnectTimeout(3000)
.setSocketTimeout(3000) // read time out
.build();
httpPost.setConfig(config); // 请求配置

CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
int responseCode = httpResponse.getStatusLine().getStatusCode();
System.out.println("【状态码:" + responseCode + "】");
InputStream in = httpResponse.getEntity().getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
StringBuffer sb = new StringBuffer();
String readLine = null;
while ((readLine = bufferedReader.readLine()) != null) {
sb.append(readLine);
}
System.out.println("返回报文:" + sb.toString());
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
System.out.println("请求异常");
return null;
}

}

public static String fileNameEncoder(HttpServletRequest request, String fileName) throws Exception {
String[] IEBrowserSignals = {"MSIE", "Trident", "Edge"};
String userAgent = request.getHeader("User-Agent");

boolean IEBrowser = false;
for (String signal : IEBrowserSignals) {
if (userAgent.contains(signal)) {
IEBrowser = true;
}
}
if(IEBrowser){
//IE浏览器的乱码问题解决
fileName = URLEncoder.encode(fileName, "UTF-8");
}else {
fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
}
return fileName;
}


public static void main(String[] args) throws UnsupportedEncodingException {
/*Map<String, Object> map = new HashMap<String, Object>();
map.put("phone", "13770994523");
map.put("company_name", "公司2");
map.put("customer_name", "小王");
System.out.println(JSONObject.toJSON(map).toString());

String resultJson = sendPost("http://www.yunzhangfang.com/api/xcx", JSONObject.toJSON(map).toString());

ObjectMapper mapper = new ObjectMapper();
try {
Map<String,Object> m = mapper.readValue(resultJson, Map.class);
System.out.println(m.get("code"));
System.out.println(m.get("msg"));
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} */
// try {
// String str = getRespInputContent("http://prd-rpt-republish-1257122416.cos.ap-shanghai.myqcloud.com/key358983180281184256?sign=q-sign-algorithm%3Dsha1%26q-ak%3DAKIDkT5ZwBPOILzqtq9VdJ4lHcljYBg7OXTM%26q-sign-time%3D1568788296%3B1568790096%26q-key-time%3D1568788296%3B1568790096%26q-header-list%3D%26q-url-param-list%3D%26q-signature%3Dafc0155840122e01218974c222910034a4444b0e");
// System.out.println("解析到的值::::::"+str);
// } catch (Exception e) {
// e.printStackTrace();
// }

//1. 创建目录
Map<String, String> map = new HashMap<>();
map.put("dir", "/test3444");
String json = JSON.toJSONString(map);
System.out.println(json);
String result = sendPost("http://221.226.82.254:38888/owncloud/mkdir?token=553EFBD8-B8F1-11E9-B9A6-1062E55BFDFE",json);
System.out.println(result);
Map<String, String> maps = (Map)JSON.parse(result);
System.out.println(MapUtils.getString(maps, "data"));

//2. 上传文件
// File file = new File("/Users/liusiyuan/yzf/demo2.txt");
// Map<String, String> map = new HashMap<>();
// map.put("dir", "/test3/");
// String result = postUploadFile("http://221.226.82.254:38888/owncloud/uploadfile?token=553EFBD8-B8F1-11E9-B9A6-1062E55BFDFE", map, file);
// System.out.println(result);
//
// Map<String, String> maps = (Map)JSON.parse(result);
// String dataMapStr = MapUtils.getString(maps, "data");
// Map<String, String> urlMaps = (Map)JSON.parse(dataMapStr);
// String url = MapUtils.getString(urlMaps, "target");
// System.out.println(url);


}




}
posted @ 2021-09-24 10:09  问道于盲  阅读(99)  评论(0编辑  收藏  举报