Java请求调用参数格式为form-data类型的接口

时间:2025-03-20 07:47:18
public static String doPostForm(String url, HashMap<String, String> map) throws Exception { String result = ""; CloseableHttpClient client = null; CloseableHttpResponse response = null; RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(550000).setConnectTimeout(550000) .setConnectionRequestTimeout(550000).setStaleConnectionCheckEnabled(true).build(); client = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build(); // client = (); URIBuilder uriBuilder = new URIBuilder(url); HttpPost httpPost = new HttpPost(uriBuilder.build()); httpPost.setHeader("Connection", "Keep-Alive"); httpPost.setHeader("Charset", "UTF-8"); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); List<NameValuePair> params = new ArrayList<NameValuePair>(); while (it.hasNext()) { Map.Entry<String, String> entry = it.next(); NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue()); params.add(pair); } httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); try { response = client.execute(httpPost); if (response != null) { HttpEntity resEntity = response.getEntity(); if (resEntity != null) { result = EntityUtils.toString(resEntity, "UTF-8"); } } } catch (ClientProtocolException e) { throw new RuntimeException("创建连接失败" + e); } catch (IOException e) { throw new RuntimeException("创建连接失败" + e); } return result; }