| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368 |
- package me.zhengjie.base.util;
- import java.io.*;
- import java.net.*;
- import java.text.MessageFormat;
- import java.util.*;
- import com.alibaba.fastjson.JSONObject;
- import cfca.trustsign.common.vo.cs.SignKeywordVO;
- import cfca.trustsign.common.vo.cs.UploadSignInfoVO;
- public class HttpUtil {
- /**
- * 默认超时时间为30秒
- */
- private static int DEFAULT_TIME_OUT = 1800000000;
- /**
- * jdk 原生 http post 请求,默认超时时间为30秒
- *
- * @param url 请求地址
- * @param json 入参String
- * @return respone的body
- */
- public static String sendPost(String url, String json) {
- return sendPost(url, json, DEFAULT_TIME_OUT);
- }
- /**
- * JDK原生post请求
- *
- * @param url 访问地址
- * @param body request请求体
- * @param timeOut 超时时间,单位毫秒
- * @return 响应体string
- */
- public static String sendPost(String url, String body, int timeOut) {
- URLConnection conn = null;
- try {
- URL realUrl = new URL(url);
- // 打开和URL之间的连接
- conn = realUrl.openConnection();
- // 设置通用的请求头属性
- conn.setRequestProperty("Content-Type", "application/json");
- conn.setRequestProperty("accept", "*/*");
- conn.setRequestProperty("connection", "Keep-Alive");
- conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
- conn.setRequestProperty("charsert", "utf-8");
- conn.setConnectTimeout(timeOut);
- conn.setReadTimeout(timeOut);
- // 发送POST请求必须设置如下两行
- conn.setDoOutput(true);
- conn.setDoInput(true);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return sendRequest(conn, body, "utf-8");
- }
- private static String sendRequest(URLConnection conn, String body, String charSet) {
- PrintWriter out = null;
- InputStreamReader ir;
- BufferedReader in = null;// 读取响应输入流
- StringBuilder stringBuilder = null;
- try {
- if (body != null) {
- out = new PrintWriter(conn.getOutputStream()); // 用PrintWriter进行包装
- out.println(body);
- // flush输出流的缓冲
- out.flush();
- }
- ir = new InputStreamReader(conn.getInputStream(), charSet);
- in = new BufferedReader(ir);
- String line;
- stringBuilder = new StringBuilder();
- while ((line = in.readLine()) != null) {
- stringBuilder.append(line);
- }
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- // 使用finally块来关闭输出流、输入流
- finally {
- try {
- if (out != null) {
- out.close();
- }
- if (in != null) {
- in.close();
- }
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- if (stringBuilder == null)
- return null;
- return stringBuilder.toString();
- }
- /***
- * 向指定URL发送POST方法的请求
- *
- * @param apiUrl
- * @param data
- * @param headers
- * @param encoding
- * @return
- * @throws Exception
- */
- public static String sendPOST(String apiUrl, String data, LinkedHashMap<String, String> headers, String encoding) throws Exception {
- // 获得响应内容
- String http_RespContent = null;
- HttpURLConnection httpURLConnection = null;
- int http_StatusCode = 0;
- String http_RespMessage = null;
- try {
- // 建立连接
- URL url = new URL(apiUrl);
- httpURLConnection = (HttpURLConnection) url.openConnection();
- // 需要输出
- httpURLConnection.setDoOutput(true);
- // 需要输入
- httpURLConnection.setDoInput(true);
- // 不允许缓存
- httpURLConnection.setUseCaches(false);
- // HTTP请求方式
- httpURLConnection.setRequestMethod("POST");
- // 设置Headers
- if (null != headers) {
- for (String key : headers.keySet()) {
- httpURLConnection.setRequestProperty(key, headers.get(key));
- }
- }
- // 连接会话
- httpURLConnection.connect();
- if (data != null) {
- // 建立输入流,向指向的URL传入参数
- DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
- // 设置请求参数
- dos.write(data.getBytes(encoding));
- dos.flush();
- dos.close();
- }
- // 获得响应状态(HTTP状态码)
- http_StatusCode = httpURLConnection.getResponseCode();
- // 获得响应消息(HTTP状态码描述)
- http_RespMessage = httpURLConnection.getResponseMessage();
- // 获得响应内容
- if (HttpURLConnection.HTTP_OK == http_StatusCode) {
- // 返回响应结果
- http_RespContent = getResponseContent(httpURLConnection);
- } else {
- // 返回非200状态时响应结果
- http_RespContent = getErrorResponseContent(httpURLConnection);
- String msg =
- MessageFormat.format("请求失败: Http状态码 = {0} , {1}", http_StatusCode, http_RespMessage);
- System.out.println(msg);
- }
- } catch (UnknownHostException e) {
- String message = MessageFormat.format("网络请求时发生异常: {0}", e.getMessage());
- Exception ex = new Exception(message);
- ex.initCause(e);
- throw ex;
- } catch (MalformedURLException e) {
- String message = MessageFormat.format("格式错误的URL: {0}", e.getMessage());
- Exception ex = new Exception(message);
- ex.initCause(e);
- throw ex;
- } catch (IOException e) {
- String message = MessageFormat.format("网络请求时发生异常: {0}", e.getMessage());
- Exception ex = new Exception(message);
- ex.initCause(e);
- throw ex;
- } catch (Exception e) {
- String message = MessageFormat.format("网络请求时发生异常: {0}", e.getMessage());
- Exception ex = new Exception(message);
- ex.initCause(e);
- throw ex;
- } finally {
- if (null != httpURLConnection) {
- httpURLConnection.disconnect();
- }
- }
- return http_RespContent;
- }
- /***
- * 读取HttpResponse响应内容
- *
- * @param httpURLConnection
- * @return
- * @throws UnsupportedEncodingException
- * @throws IOException
- */
- private static String getErrorResponseContent(HttpURLConnection httpURLConnection)
- throws UnsupportedEncodingException, IOException {
- StringBuffer contentBuffer = null;
- BufferedReader responseReader = null;
- try {
- contentBuffer = new StringBuffer();
- String readLine = null;
- responseReader =
- new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream(), "UTF-8"));
- while ((readLine = responseReader.readLine()) != null) {
- contentBuffer.append(readLine);
- }
- } finally {
- if (null != responseReader) {
- responseReader.close();
- }
- }
- return contentBuffer.toString();
- }
- /***
- * 读取HttpResponse响应内容
- *
- * @param httpURLConnection
- * @return
- * @throws UnsupportedEncodingException
- * @throws IOException
- */
- private static String getResponseContent(HttpURLConnection httpURLConnection)
- throws UnsupportedEncodingException, IOException {
- StringBuffer contentBuffer = null;
- BufferedReader responseReader = null;
- try {
- contentBuffer = new StringBuffer();
- String readLine = null;
- responseReader =
- new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
- while ((readLine = responseReader.readLine()) != null) {
- contentBuffer.append(readLine);
- }
- } finally {
- if (null != responseReader) {
- responseReader.close();
- }
- }
- return contentBuffer.toString();
- }
- /**
- * 上传文件
- *
- * @param url
- * @param header
- * @param filePath
- * @return
- */
- public static String postFile(String url, Map<String, String> header, String filePath) {
- HttpURLConnection conn = null;
- OutputStream out = null;
- String respContent = "";
- try {
- URL realUrl = new URL(url);
- // 打开和URL之间的连接
- conn = (HttpURLConnection) realUrl.openConnection();
- // 设置通用的请求头属性
- conn.setRequestProperty("Content-Type", header.get("contentType"));
- conn.setRequestProperty("Content-MD5", header.get("contentMD5"));
- // 发送POST请求必须设置如下两行
- conn.setDoOutput(true);
- conn.setDoInput(true);
- conn.setRequestMethod("PUT");
- conn.connect();
- // 上传文件内容
- out = new DataOutputStream(conn.getOutputStream());
- File file = new File(filePath);
- DataInputStream fileIS = new DataInputStream(new FileInputStream(file));
- int bytes = 0;
- byte[] bufferOut = new byte[1024];
- while ((bytes = fileIS.read(bufferOut)) != -1) {
- out.write(bufferOut, 0, bytes);
- }
- fileIS.close();
- out.flush();
- out.close();
- // 获取返回信息
- int statusCode = conn.getResponseCode();
- String respMessage = conn.getResponseMessage();
- // 获得响应内容
- if (HttpURLConnection.HTTP_OK == statusCode) {
- // 返回响应结果
- respContent = getResponseContent(conn);
- } else {
- // 返回非200状态时响应结果
- respContent = getErrorResponseContent(conn);
- String msg = MessageFormat.format("请求失败: Http状态码 = {0} , {1}", statusCode, respMessage);
- System.out.println(msg);
- }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- if (out != null) {
- out.close();
- }
- if (conn != null) {
- conn.disconnect();
- }
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- return respContent;
- }
- public static void main(String[] args) throws Exception {
- int i = 0;
- String pdf = "gzs.pdf";
- String localUrl = "https://flowbb.show.xjrkj.com/demo";
- // String localUrl = "http://localhost:8000/demo";
- List<UploadSignInfoVO> notaryUserInfos = new ArrayList<>();
- // --------------------------------------------------------------------------------------
- UploadSignInfoVO xj = new UploadSignInfoVO();
- xj.setUserId("E06DAAB5F6894542E05312016B0AC8F1");
- xj.setSealId("E06DAB4AFAEF4DB7E05311016B0A5154");
- xj.setLocation("210.74.41.0");
- xj.setAuthorizationTime("20220214171200");
- notaryUserInfos.add(xj);
- // UploadSignInfoVO ttt = new UploadSignInfoVO();
- // ttt.setUserId("E658B207485F141AE05311016B0A5F19");
- // ttt.setSealId("E658C5DBBAF1340DE05311016B0A3C4D");
- // ttt.setLocation("210.74.41.0");
- // ttt.setAuthorizationTime("20220214171200");
- // notaryUserInfos.add(ttt);
- UploadSignInfoVO wcc = new UploadSignInfoVO();
- wcc.setUserId("E150B42F789F53D8E05311016B0A24B0");
- wcc.setSealId("E150B90286FA6E31E05312016B0A03F2");
- wcc.setLocation("210.74.41.0");
- wcc.setAuthorizationTime("20220214171200");
- notaryUserInfos.add(wcc);
- for (UploadSignInfoVO user : notaryUserInfos) {
- String x = String.valueOf(10 + i * 70);
- i++;
- SignKeywordVO keywordNotaryUser = CFCACertUtil.getSignKeywork("签章:", x, "0", "80", "40");
- CFCACertUtil.setSignInfoDefault(user, keywordNotaryUser);
- }
- // --------------------------------------------------------------------------------------
- // SignKeywordVO keywordNotaryOffice = CFCACertUtil.getSignKeywork("签章", "0", "0", "150", "150");
- // if (notaryOffice != null) {
- // setSignInfoDefault(notaryOffice, keywordNotaryOffice);
- // signInfos.add(notaryOffice);
- // }
- String result = HttpUtil.sendPost(localUrl + "/notarySign?fileName=" + pdf,
- JSONObject.toJSONString(notaryUserInfos));
- JSONObject jsonObj = JSONObject.parseObject(result);
- System.out.println(jsonObj.getString("msg") + ".pdf");
- Map<String, String> param = new HashMap<String, String>();
- param.put("contractNo", jsonObj.getString("msg"));
- result = HttpUtil.sendPost(localUrl + "/download", JSONObject.toJSONString(param));
- System.out.println(result);
- // System.out.println("用户近6个月平均话费评分:" + result);
- }
- }
|