http請求java
import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; private String findFromRemote(Date date){ int socketTimeout = 10*1000; int connectTimeout = 10*1000; String result = ""; CloseableHttpClient httpClient = HttpClientBuilder.create().build(); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout) .setConnectTimeout(connectTimeout).build(); try { HttpPost httpPost = new HttpPost(REMOTE_SERVER_URL); // 設置請求器的配置 httpPost.setConfig(requestConfig); List<NameValuePair> pair = new ArrayList<NameValuePair>(2); pair.add(new BasicNameValuePair("date", "2017-3-22")); pair.add(new BasicNameValuePair("key","0ad9fcd5282912bc8b7b5655a3718e78")); httpPost.setEntity(new UrlEncodedFormEntity(pair, "UTF-8")); HttpResponse httpResponse = httpClient.execute(httpPost); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { } } return result; }
https 請求:apache
import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; 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.HttpPost; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; //method String result = ""; final String url = "https://v.juhe.cn/calendar/day?date=2015-1-1&key=0ad9fcd5282912bc8b7b5655a3718e78"; CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; try { HttpPost httpPost = new HttpPost(url); if (url.startsWith("https")) { // https訪問 httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); } else { // 普通的http調用 httpClient = HttpClients.createDefault(); } List<NameValuePair> nvps = new ArrayList<NameValuePair>(); // nvps.add(new BasicNameValuePair("mobile", "1111222")); // nvps.add(new BasicNameValuePair("md5Password", "md5加密的密文")); // httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8")); try { response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { result = EntityUtils.toString(response.getEntity(), "UTF-8"); } } catch (IOException e) { e.printStackTrace(); } try { } finally { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } } finally { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } return result;
證書加載cookie
/** * 初始化證書 * * @param certLocalPath * 證書地址 * @param certPassword * 證書密碼 * @param socketTimeout * @param connectTimeout */ private static void initSsl(String certLocalPath, String certPassword, CloseableHttpClient httpClient, String responseStr) { try { // 得到密匙庫 KeyStore keyStore = KeyStore.getInstance("PKCS12"); FileInputStream instream = new FileInputStream(new File(certLocalPath));// 加載本地的證書進行https加密傳輸 try { keyStore.load(instream, certPassword.toCharArray());// 設置證書密碼 } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } finally { instream.close(); } // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, certPassword.toCharArray()).build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, new DefaultHostnameVerifier()); httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); } catch (KeyManagementException e) { responseStr = "{\"is_success\":\"F\",\"error_code\":\"KeyManagementException\"}"; } catch (UnrecoverableKeyException e) { responseStr = "{\"is_success\":\"F\",\"error_code\":\"UnrecoverableKeyException\"}"; } catch (KeyStoreException e) { responseStr = "{\"is_success\":\"F\",\"error_code\":\"KeyStoreException\"}"; } catch (FileNotFoundException e) { responseStr = "{\"is_success\":\"F\",\"error_code\":\"FileNotFoundException\"}"; } catch (NoSuchAlgorithmException e) { responseStr = "{\"is_success\":\"F\",\"error_code\":\"NoSuchAlgorithmException\"}"; } catch (ClientProtocolException e) { responseStr = "{\"is_success\":\"F\",\"error_code\":\"ClientProtocolException\"}"; } catch (IllegalStateException e) { responseStr = "{\"is_success\":\"F\",\"error_code\":\"IllegalStateException\"}"; } catch (IOException e) { responseStr = "{\"is_success\":\"F\",\"error_code\":\"IOException\"}"; } } /** * 創建post請求 * * @param url * @param nameValuePair * @param timeoutConnection * 設置鏈接超時時間(毫秒) * @param timeoutSocket * 設置默認的套接字超時(so_timeout毫秒)。這是爲了等待數據超時。 * @param charset * 編碼類型 * @param certLocalPath * 證書地址 * @param certPassword * 證書密碼 * @param isNeedSssl * 是否須要證書 * @return String 請求返回結果 */ public static String buildPostRequest(String url, Map<String, String> nameValuePair, int timeoutConnection, int timeoutSocket, String charset, String certLocalPath, String certPassword, boolean isNeedSssl) { String responseStr = ""; // 得到httpclient對象 CloseableHttpClient httpClient = HttpClients.createDefault(); try { if (isNeedSssl) { initSsl(certLocalPath, certPassword, httpClient, responseStr); } // 根據默認超時限制初始化requestConfig RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeoutSocket) .setConnectTimeout(timeoutConnection).build(); HttpPost httpPost = new HttpPost(url); UrlEncodedFormEntity entity = null; // 設置httpPost請求參數 if (null != charset && (charset.compareToIgnoreCase("GBK") == 0 || charset.compareToIgnoreCase("GB3212") == 0)) { entity = new UrlEncodedFormEntity(generatNamePair(nameValuePair), "GBK"); } else { entity = new UrlEncodedFormEntity(generatNamePair(nameValuePair), "UTF-8"); } entity.setContentEncoding(charset); httpPost.addHeader("Content-Type", "text/xml"); httpPost.setEntity(entity); // 設置請求器的配置 httpPost.setConfig(requestConfig); // 使用execute方法發送HTTP Post請求,並返回HttpResponse對象 HttpResponse httpResponse = httpClient.execute(httpPost); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { responseStr = EntityUtils.toString(httpResponse.getEntity(), "UTF-8"); } else { responseStr = "{\"error_response\":\"request failed\"}"; } } catch (ClientProtocolException e) { responseStr = "{\"is_success\":\"F\",\"error_code\":\"ClientProtocolException\"}"; } catch (IllegalStateException e) { responseStr = "{\"is_success\":\"F\",\"error_code\":\"IllegalStateException\"}"; } catch (IOException e) { responseStr = "{\"is_success\":\"F\",\"error_code\":\"IOException\"}"; } finally { try { httpClient.close(); } catch (IOException e) { } } return responseStr; }
cookies 獲取app
public void doPost(String url, Map<String, String> param, Map<String, String> requestHeader, List<Cookie> cookies) throws IOException { DBHttpClientResponse _response = null; // 建立http POST請求 HttpPost httpPost = new HttpPost(url); httpPost.setConfig(this.config); //添加參數 List<NameValuePair> nvps = new ArrayList<>(); if (param != null && param.size() != 0) { for (String key : param.keySet()) { nvps.add(new BasicNameValuePair(key, param.get(key))); } httpPost.setEntity(new UrlEncodedFormEntity(nvps)); } //設置請求頭 if (requestHeader == null) { requestHeader = HEADMAP; } for (String str : requestHeader.keySet()) { httpPost.setHeader(str, requestHeader.get(str)); } //添加cookieStore 請求完後,就能夠從這個變量中獲取cookie CookieStore cookieStore = new BasicCookieStore(); //建立httpclient CloseableHttpClient client = HttpClients.custom() .setDefaultCookieStore(cookieStore).build(); CloseableHttpResponse response; response = client.execute(httpPost); List<Cookie> cookies = cookieStore.getCookies(); //獲得的cookies response.close(); client.close(); }
添加cookiessocket
public void doPost(String url, Map<String, String> param, Map<String, String> requestHeader, List<Cookie> cookies) throws IOException { DBHttpClientResponse _response = null; // 建立http POST請求 HttpPost httpPost = new HttpPost(url); httpPost.setConfig(this.config); //添加參數 List<NameValuePair> nvps = new ArrayList<>(); if (param != null && param.size() != 0) { for (String key : param.keySet()) { nvps.add(new BasicNameValuePair(key, param.get(key))); } httpPost.setEntity(new UrlEncodedFormEntity(nvps)); } //設置請求頭 if (requestHeader == null) { requestHeader = HEADMAP; } for (String str : requestHeader.keySet()) { httpPost.setHeader(str, requestHeader.get(str)); } //添加cookie if (cookies != null && cookies.size() != 0) { StringBuilder cookiesBuilder = new StringBuilder(); for (String str : cookies.keySet()) { cookiesBuilder.append(str + "=" + cookies.get(str) + ";"); } cookiesBuilder.deleteCharAt(cookiesBuilder.length() - 1); httpPost.setHeader("Cookie", cookiesBuilder.toString()); } //添加cookieStore 請求完後,就能夠從這個變量中獲取cookie CookieStore cookieStore = new BasicCookieStore(); //建立httpclient CloseableHttpClient client = HttpClients.custom() .setDefaultCookieStore(cookieStore).build(); CloseableHttpResponse response; response = client.execute(httpPost); List<Cookie> cookies = cookieStore.getCookies(); //獲得的cookies response.close(); client.close(); }