使用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使用基本教程