123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- package com.redxun.search.utils;
- import lombok.extern.slf4j.Slf4j;
- import java.io.*;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.util.Map;
- /**
- *
- */
- @Slf4j
- public final class HttpUtil {
- static final String POST = "POST";
- static final String GET = "GET";
- static final int CONN_TIMEOUT = 30000;// ms
- static final int READ_TIMEOUT = 30000;// ms
- /**
- * post 方式发送http请求.
- *
- * @param strUrl
- * @param reqData
- * @return
- */
- public static byte[] doPost(String strUrl,Map<String ,Object> headerMap, byte[] reqData) {
- return send(strUrl, POST, reqData,headerMap);
- }
- /**
- * get方式发送http请求.
- *
- * @param strUrl
- * @return
- */
- public static byte[] doGet(String strUrl) {
- return send(strUrl, GET, null,null);
- }
- /**
- * @param strUrl
- * @param reqmethod
- * @param reqData
- * @return
- */
- public static byte[] send(String strUrl, String reqmethod, byte[] reqData,Map<String ,Object> headerMap) {
- try {
- URL url = new URL(strUrl);
- HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
- // 携带请求头
- httpcon.setRequestProperty("signature",(String) headerMap.get("signature"));
- httpcon.setRequestProperty("businessKey",(String) headerMap.get("businessKey"));
- httpcon.setRequestProperty("userId",(String) headerMap.get("userId"));
- httpcon.setDoOutput(true);
- httpcon.setDoInput(true);
- httpcon.setUseCaches(false);
- httpcon.setInstanceFollowRedirects(true);
- httpcon.setConnectTimeout(CONN_TIMEOUT);
- httpcon.setReadTimeout(READ_TIMEOUT);
- httpcon.setRequestMethod(reqmethod);
- httpcon.connect();
- if (reqmethod.equalsIgnoreCase(POST)) {
- OutputStream os = httpcon.getOutputStream();
- os.write(reqData);
- os.flush();
- os.close();
- }
- BufferedReader in = new BufferedReader(new InputStreamReader(httpcon.getInputStream(),"utf-8"));
- String inputLine;
- StringBuilder bankXmlBuffer = new StringBuilder();
- while ((inputLine = in.readLine()) != null) {
- bankXmlBuffer.append(inputLine);
- }
- in.close();
- httpcon.disconnect();
- return bankXmlBuffer.toString().getBytes();
- } catch (Exception ex) {
- log.error(ex.toString(), ex);
- return null;
- }
- }
- }
|