使用httpClient模擬提交多表單部件
阿新 • • 發佈:2018-11-29
使用httpClient模擬提交多表單部件
- 在pom.xml加入對httpclient的必需的jar包的依賴
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency> //httpclient快取 <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient-cache</artifactId> <version>4.5</version> </dependency> //http的mime型別都在這裡面 <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.3.2</version> </dependency>
- 程式碼
/** * 帶引數的Post請求 * * @param url 請求URL * @param paramMap 請求引數 * @return */ public static String doPost(String url, Map<String, String> paramMap) { CloseableHttpClient httpclient = null; CloseableHttpResponse response = null; String result = ""; try { httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(35000) .setConnectionRequestTimeout(35000) .setSocketTimeout(60000) .build(); httpPost.setConfig(requestConfig); if (null != paramMap && paramMap.size()>0) { List<NameValuePair> nvps = new ArrayList<NameValuePair>(); Set<Map.Entry<String, String>> set = paramMap.entrySet(); Iterator<Map.Entry<String, String>> it = set.iterator(); while (it.hasNext()) { Map.Entry<String, String> mapEntry = it.next(); nvps.add(new BasicNameValuePair(mapEntry.getKey(), new String(mapEntry.getValue().getBytes("UTF-8"),"iso8859-1"))); } httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); } response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); result = EntityUtils.toString(entity); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (null != response) { response.close(); } if (null != httpclient) { httpclient.close(); } } catch (IOException e) { e.printStackTrace(); } } return result; }```
httpclient的基礎用法請檢視此連結 httpclient使用基本教程