| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345 |
- package com.dk.common.util;
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.JSONObject;
- import com.dk.common.response.ResponseCodeEnum;
- import com.dk.common.response.ResponseResultUtil;
- import com.dk.common.response.ResponseResultVO;
- import lombok.extern.slf4j.Slf4j;
- import org.apache.commons.io.FileUtils;
- import org.apache.http.Consts;
- import org.apache.http.entity.mime.HttpMultipartMode;
- import org.springframework.http.client.MultipartBodyBuilder;
- import org.springframework.web.multipart.MultipartFile;
- import org.apache.http.HttpEntity;
- import org.apache.http.client.methods.CloseableHttpResponse;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.entity.ContentType;
- import org.apache.http.entity.mime.MultipartEntityBuilder;
- import org.apache.http.impl.client.CloseableHttpClient;
- import org.apache.http.impl.client.HttpClients;
- import org.apache.http.util.EntityUtils;
- import java.io.*;
- import java.net.HttpURLConnection;
- import java.net.SocketTimeoutException;
- import java.net.URL;
- import java.nio.charset.Charset;
- import java.nio.charset.StandardCharsets;
- import java.util.Map;
- /**
- * @author H_x_d
- * @date_time 2020-07-16 11:44
- * @description com.dongke.base.util.HttpHelper.java
- */
- @Slf4j
- public class HttpUtils {
- public static ResponseResultVO<JSONObject> post(String url) {
- return httpPost(url, null, false, null, null, null);
- }
- public static ResponseResultVO<JSONObject> post(String url, Object object) {
- return httpPost(url, object, false, null, null, null);
- }
- public static ResponseResultVO<JSONObject> post(String url, Map<String, String> requestProperty) {
- return httpPost(url, null, false, null, requestProperty, null);
- }
- public static ResponseResultVO<JSONObject> post(String url, Object object, Integer overTime) {
- return httpPost(url, object, false, null, null, overTime);
- }
- public static ResponseResultVO<JSONObject> post(String url, Object object, Map<String, String> requestProperty) {
- return httpPost(url, object, false, null, requestProperty, null);
- }
- public static ResponseResultVO<JSONObject> post(String url, Object object, Map<String, String> requestProperty, Integer overTime) {
- return httpPost(url, object, false, null, requestProperty, overTime);
- }
- public static ResponseResultVO<String> postReturnFile(String url, Object object, String fileUrl) {
- return httpPost(url, object, true, fileUrl, null, null);
- }
- public static ResponseResultVO httpPost(String url, Object object, boolean returnFile, String fileUrl, Map<String, String> requestProperty, Integer overTime) {
- log.info("post_url-> " + url);
- InputStream inputStream = null;
- HttpURLConnection connection = null;
- FileOutputStream fos = null;
- ByteArrayOutputStream boa = null;
- OutputStreamWriter outputStreamWriter = null;
- try {
- //获取位置服务的地址
- URL u = new URL(url);
- //打开连接
- connection = (HttpURLConnection) u.openConnection();
- connection.setDoOutput(true);
- connection.setDoInput(true);
- connection.setRequestMethod("POST");
- connection.setUseCaches(false);
- connection.setInstanceFollowRedirects(true);
- // 超时时间
- if (overTime==null) {
- connection.setConnectTimeout(3000);
- connection.setReadTimeout(120000);
- }else{
- connection.setConnectTimeout(overTime);
- connection.setReadTimeout(overTime);
- }
- connection.setRequestProperty("Content-Type", "application/json;charset:utf-8");
- if (requestProperty != null) {
- for (String key : requestProperty.keySet()) {
- connection.setRequestProperty(key, requestProperty.get(key));
- }
- }
- connection.connect();
- outputStreamWriter = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
- log.info("post_param-> \n" + JSONObject.toJSONString(object));
- outputStreamWriter.append(JSONObject.toJSONString(object));
- outputStreamWriter.flush();
- outputStreamWriter.close();
- int responseCode = connection.getResponseCode();
- log.info("responseCode-> " + responseCode);
- if (responseCode == HttpURLConnection.HTTP_OK) {
- inputStream = connection.getInputStream();
- if (returnFile) {
- File file = new File(fileUrl);
- fos = new FileOutputStream(file);
- byte[] buffer = new byte[4096];
- int len = -1;
- while ((len = inputStream.read(buffer)) != -1) {
- fos.write(buffer, 0, len);
- }
- fos.close();
- inputStream.close();
- log.info("post_result-> \n file url:{}", fileUrl);
- return ResponseResultUtil.success(fileUrl);
- } else {
- boa = new ByteArrayOutputStream();
- int len = 0;
- byte[] buffer = new byte[1024];
- while ((len = inputStream.read(buffer)) != -1) {
- boa.write(buffer, 0, len);
- }
- // inputStream.close();
- // boa.close();
- byte[] result = boa.toByteArray();
- String temp = new String(result);
- String res = "";
- // 识别编码
- if (temp.contains("gb2312")) {
- log.info("解码类型:gb2312");
- res = new String(result, "gb2312");
- } else {
- // log.info("解码类型:utf-8");
- res = new String(result, StandardCharsets.UTF_8);
- }
- log.info("post_result-> \n" + res);
- return ResponseResultUtil.success(JSONObject.parseObject(res));
- //将流转换为字符串。
- // byte[] b = new byte[4096];
- // for (int n; (n = inputStream.read(b)) != -1;) {
- // out.append(new String(b, 0, n, StandardCharsets.UTF_8));
- // }
- // inputStream.close();
- // log.info("post_result-> \n"+out.toString());
- // return ResponseResultUtil.success(JSONObject.parseObject(out.toString()));
- }
- } else {
- log.error("post_code-> " + responseCode);
- return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL, String.valueOf(responseCode));
- }
- } catch (SocketTimeoutException e) {
- log.error("post_error:{}", e.toString(), e);
- return ResponseResultUtil.error(ResponseCodeEnum.SERVER_CONNECT_OUT, e.toString());
- } catch (Exception e) {
- log.error("post_error:{}", e.toString(), e);
- return ResponseResultUtil.error(ResponseCodeEnum.SERVER_ERROR, e.toString());
- } finally {
- // 断开连接、关闭流
- if (connection!=null){
- connection.disconnect();
- }
- try {
- if (inputStream!=null){
- inputStream.close();
- }
- if (fos!=null){
- fos.close();
- }
- if (boa!=null){
- boa.close();
- }
- if (outputStreamWriter!=null){
- outputStreamWriter.close();
- }
- } catch (IOException e) {
- log.error(e.toString(), e);
- }
- }
- }
- public static ResponseResultVO<JSONObject> get(String url) {
- return httpGet(url, null, null);
- }
- public static ResponseResultVO<JSONObject> get(String url, Map<String, String> requestProperty) {
- return httpGet(url, requestProperty, null);
- }
- public static ResponseResultVO<JSONObject> get(String url, Integer overTime) {
- return httpGet(url, null, overTime);
- }
- public static ResponseResultVO<JSONObject> get(String url, Map<String, String> requestProperty, Integer overTime) {
- return httpGet(url, requestProperty, overTime);
- }
- public static ResponseResultVO<JSONObject> httpGet(String url, Map<String, String> requestProperty, Integer overTime) {
- log.info("get_url-> " + url);
- BufferedReader br = null;
- HttpURLConnection connection = null;
- try {
- URL u = new URL(url);
- connection = (HttpURLConnection) u.openConnection();
- // 超时时间
- if (overTime==null) {
- connection.setConnectTimeout(3000);
- connection.setReadTimeout(120000);
- }else{
- connection.setConnectTimeout(overTime);
- connection.setReadTimeout(overTime);
- }
- connection.setRequestProperty("Content-Type", "application/json;charset:utf-8");
- if (requestProperty != null) {
- for (String key : requestProperty.keySet()) {
- connection.setRequestProperty(key, requestProperty.get(key));
- }
- }
- connection.connect();// 连接会话
- // 获取输入流
- br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
- String line;
- StringBuilder sb = new StringBuilder();
- while ((line = br.readLine()) != null) {
- sb.append(line);
- }
- // br.close();// 关闭流
- // connection.disconnect();// 断开连接
- log.info("get_result-> \n" + sb.toString());
- return ResponseResultUtil.success(JSONObject.parseObject(sb.toString()));
- } catch (SocketTimeoutException e) {
- log.error("get_error:{}", e.toString(), e);
- return ResponseResultUtil.error(ResponseCodeEnum.SERVER_CONNECT_OUT, e.toString());
- } catch (Exception e) {
- log.error("get_error:{}", e.toString(), e);
- return ResponseResultUtil.error(ResponseCodeEnum.SERVER_ERROR, e.toString());
- } finally {
- // 断开连接 关闭流
- if (connection!=null){
- connection.disconnect();
- }
- try {
- if (br!=null) {
- br.close();
- }
- } catch (IOException e) {
- log.error(e.toString(), e);
- }
- }
- }
- public static ResponseResultVO<JSONObject> postFile(String url, MultipartFile file) {
- return postFormData(url, null, file);
- }
- public static ResponseResultVO<JSONObject> postFile(String url, Object object, MultipartFile file) {
- return postFormData(url, object, file);
- }
- public static ResponseResultVO<JSONObject> postForm(String url, Object object) {
- return postFormData(url, object, null);
- }
- public static ResponseResultVO<JSONObject> postFormData(String url, Object object, MultipartFile file) {
- log.info("postFormData, url:\n{}", url);
- CloseableHttpClient httpClient = HttpClients.createDefault();
- HttpPost httpPost = new HttpPost(url);
- MultipartEntityBuilder builder = MultipartEntityBuilder.create();
- if (object!=null){
- JSONObject param = JSONObject.parseObject(JSONObject.toJSONString(object));
- param.keySet().forEach(key -> {
- log.info("key:{},value:{}",key,param.getString(key));
- builder.addTextBody(key, param.getString(key), ContentType.create("text/plain", StandardCharsets.UTF_8));
- });
- }
- try {
- File f = null;
- if (file != null && file.getOriginalFilename() == null) {
- return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL.getCode(), "文件不存在");
- } else if (file != null && file.getOriginalFilename() != null) {
- log.info("post form data, file->\nname:{},size:{},", file.getName(), file.getSize());
- f = new File(file.getOriginalFilename());
- FileUtils.copyInputStreamToFile(file.getInputStream(), f);
- builder.addBinaryBody(
- "file",
- new FileInputStream(f),
- ContentType.APPLICATION_OCTET_STREAM,
- f.getName()
- );
- }
- HttpEntity multipart = builder.build();
- httpPost.setEntity(multipart);
- CloseableHttpResponse response = httpClient.execute(httpPost);
- HttpEntity responseEntity = response.getEntity();
- String sResponse = EntityUtils.toString(responseEntity, "UTF-8");
- log.info("post form data response->\n{}", sResponse);
- JSONObject res = JSONObject.parseObject(sResponse);
- // 会在本地产生临时文件,用完后需要删除
- if (f != null && f.exists()) {
- f.delete();
- }
- return ResponseResultUtil.success(res);
- } catch (SocketTimeoutException e) {
- log.error("postFormData_error:{}", e.toString(), e);
- return ResponseResultUtil.error(ResponseCodeEnum.SERVER_CONNECT_OUT, e.toString());
- } catch (Exception e) {
- log.error(e.toString(), e);
- return ResponseResultUtil.error(ResponseCodeEnum.SERVER_ERROR, e.toString());
- }
- }
- }
|