公司沒網,所有要請求接口需要設置代理。
doGet postJson 和 不進行代理請求的postJsonNotProxy
import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.ParseException; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.config.RequestConfig; 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.entity.StringEntity; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicHeader; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; /** * 封裝了一些採用 HttpClient發送HTTP請求的方法 */ public class HttpClientUtils { /** * 連接超時時間 */ private static int CONNECT_TIME_OUT = 15 * 1000; /** * 讀取超時時間 */ private static int READ_TIME_OUT = 30 * 1000;//40秒 private HttpClientUtils() { } public static String doGet(String url) { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; String result = ""; try { HttpHost proxy = new HttpHost("代理網址", 8080, "http"); CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials("賬號", "密碼")); httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider).build(); // 創建httpGet遠程連接實例 HttpGet httpGet = new HttpGet(url); // 設置請求頭信息,鑑權 // httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0"); // 設置配置請求參數 RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 連接主機服務超時時間 .setConnectionRequestTimeout(35000)// 請求超時時間 .setSocketTimeout(60000)// 數據讀取超時時間 .setProxy(proxy) .build(); // 爲httpGet實例設置配置 httpGet.setConfig(requestConfig); // 執行get請求得到返回對象 response = httpClient.execute(httpGet); // 通過返回對象獲取返回數據 HttpEntity entity = response.getEntity(); // 通過EntityUtils中的toString方法將結果轉換爲字符串 result = EntityUtils.toString(entity); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 關閉資源 if (null != response) { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != httpClient) { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } /** * 發送post 請求(json格式) * * @param reqURL * @param jsonDataStr * @return result */ public static String postJson(String reqURL, String jsonDataStr) { CloseableHttpClient httpClient = null; HttpPost httpPost = null; String responseResult = null; CloseableHttpResponse response = null; try { HttpHost proxy = new HttpHost("代理網址", 8080, "http"); CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials("賬號", "密碼")); httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider).build(); httpPost = new HttpPost(reqURL); RequestConfig requestConfig = RequestConfig.custom()// .setConnectTimeout(CONNECT_TIME_OUT)// 連接一個url的連接等待時間 .setConnectionRequestTimeout(CONNECT_TIME_OUT)// .setSocketTimeout(READ_TIME_OUT)// 讀取數據超時 .setProxy(proxy) .build(); httpPost.setConfig(requestConfig); httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json"); StringEntity entity = new StringEntity(jsonDataStr, "UTF-8"); entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING, "UTF-8")); entity.setContentType("application/json"); httpPost.setEntity(entity); response = httpClient.execute(httpPost); HttpEntity httpEntity = response.getEntity(); if (httpEntity != null) { responseResult = EntityUtils.toString(httpEntity, "UTF-8"); EntityUtils.consume(httpEntity); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { closeHttp(response, httpClient); } return responseResult; } public static String postJsonNotProxy(String reqURL, String jsonDataStr, String token) { CloseableHttpClient httpClient = null; HttpPost httpPost = null; String responseResult = null; CloseableHttpResponse response = null; try { httpClient = HttpClients.custom().build(); httpPost = new HttpPost(reqURL); RequestConfig requestConfig = RequestConfig.custom()// .setConnectTimeout(CONNECT_TIME_OUT)// 連接一個url的連接等待時間 .setConnectionRequestTimeout(CONNECT_TIME_OUT)// .setSocketTimeout(READ_TIME_OUT)// 讀取數據超時 .build(); httpPost.setConfig(requestConfig); httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json"); httpPost.setHeader("Authorization", token); StringEntity entity = new StringEntity(jsonDataStr, "UTF-8"); entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING, "UTF-8")); entity.setContentType("application/json"); httpPost.setEntity(entity); response = httpClient.execute(httpPost); HttpEntity httpEntity = response.getEntity(); if (httpEntity != null) { responseResult = EntityUtils.toString(httpEntity, "UTF-8"); EntityUtils.consume(httpEntity); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { closeHttp(response, httpClient); } return responseResult; } public static String doPostForm(String httpUrl, Map param) { HttpURLConnection connection = null; InputStream is = null; OutputStream os = null; BufferedReader br = null; String result = null; try { URL url = new URL(httpUrl); // 通過遠程url連接對象打開連接 connection = (HttpURLConnection) url.openConnection(); // 設置連接請求方式 connection.setRequestMethod("POST"); // 設置連接主機服務器超時時間:15000毫秒 connection.setConnectTimeout(15000); // 設置讀取主機服務器返回數據超時時間:60000毫秒 connection.setReadTimeout(60000); // 默認值爲:false,當向遠程服務器傳送數據/寫數據時,需要設置爲true connection.setDoOutput(true); // 默認值爲:true,當前向遠程服務讀取數據時,設置爲true,該參數可有可無 connection.setDoInput(true); // 設置傳入參數的格式:請求參數應該是 name1=value1&name2=value2 的形式。 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 設置鑑權信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0 //connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0"); // 通過連接對象獲取一個輸出流 os = connection.getOutputStream(); // 通過輸出流對象將參數寫出去/傳輸出去,它是通過字節數組寫出的(form表單形式的參數實質也是key,value值的拼接,類似於get請求參數的拼接) os.write(createLinkString(param).getBytes()); // 通過連接對象獲取一個輸入流,向遠程讀取 if (connection.getResponseCode() == 200) { is = connection.getInputStream(); // 對輸入流對象進行包裝:charset根據工作項目組的要求來設置 br = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuffer sbf = new StringBuffer(); String temp = null; // 循環遍歷一行一行讀取數據 while ((temp = br.readLine()) != null) { sbf.append(temp); sbf.append("\r\n"); } result = sbf.toString(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 關閉資源 if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != os) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } // 斷開與遠程地址url的連接 connection.disconnect(); } return result; } public static String createLinkString(Map<String, String> params) { List<String> keys = new ArrayList<String>(params.keySet()); Collections.sort(keys); StringBuilder prestr = new StringBuilder(); for (int i = 0; i < keys.size(); i++) { String key = keys.get(i); String value = params.get(key); if (i == keys.size() - 1) {// 拼接時,不包括最後一個&字符 prestr.append(key).append("=").append(value); } else { prestr.append(key).append("=").append(value).append("&"); } } return prestr.toString(); } private static void closeHttp(CloseableHttpResponse response, CloseableHttpClient httpClient) { try { if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } try { if (httpClient != null) { httpClient.close(); } } catch (IOException e) { e.printStackTrace(); } } }