1.带文件的post请求

Map<String, Object> map = new HashMap<>();
map.put("list", list);
HttpClientUtil.httpMultipartListPost(URL + accessToken, files, map, request);
public static String httpMultipartListPost(String url, MultipartFile[] files, Map<String, Object> otherParams, HttpServletRequest request) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		String result = "";
		HttpEntity httpEntity = null;
		try {
			HttpPost httpPost = new HttpPost(url);
			MultipartEntityBuilder builder = MultipartEntityBuilder.create();
			builder.setCharset(StandardCharsets.UTF_8);
			builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // 加上此行代码解决返回中文乱码问题

			// 添加文件参数
			for (MultipartFile file : files) {
				String fileName = file.getOriginalFilename();
				builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName); // 文件流
			}

			// 添加其他参数
			for (Map.Entry<String, Object> entry : otherParams.entrySet()) {
				if (entry.getKey().equals("list")) { // 跳过文件名参数和list参数
					String[] values = (String[]) entry.getValue();
					for (String value : values) {
						builder.addTextBody(entry.getKey(), value);
					}
				}else {
					builder.addTextBody(entry.getKey(), entry.getValue().toString());
				}
			}
			/*
			 * // 添加 HttpServletRequest request 参数 Enumeration<String> requestNames =
			 * request.getParameterNames(); while (requestNames.hasMoreElements()) { String
			 * paramName = requestNames.nextElement(); String[] paramValues =
			 * request.getParameterValues(paramName); for (String paramValue : paramValues)
			 * { builder.addTextBody(paramName, paramValue); } }
			 */
			httpEntity = builder.build();
			httpPost.setEntity(httpEntity);

			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity responseEntity = response.getEntity();

			if (responseEntity != null) {
				result = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

2.采用x-www-form-urlencoded的post请求

String stockUrl = "http://www.test.com:88/openapi/test";
NameValuePair[] data = {
		new NameValuePair("usertoken","test"),
		new NameValuePair("businessObjectTypeId","test"),
		new NameValuePair("filter","fMaterialNumber in ("+query+")")
};
	public static String httpPostUrlencoded(String url, NameValuePair[] data) {
		System.out.println("GetPage:" + url);

		String content = null;
		HttpClient httpClient = new HttpClient();
		PostMethod method = new PostMethod(url);
		method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") ;
		method.setRequestBody(data);
		try {
			httpClient.executeMethod(method);
//			content = new String(method.getResponseBody());
			content = method.getResponseBodyAsString();
		} catch (Exception e) {
			System.out.println("time out");
			e.printStackTrace();
		} finally {
			if (method != null) method.releaseConnection();
			httpClient.getHttpConnectionManager().closeIdleConnections(0L);
			method = null;
			httpClient = null;
		}
		return content;

	}

3.带json的post请求

String param = "{\"codebars\": \"X\"}";
String stockUrl = "https://api.test.com/openapi/stocks/";		
Map<String, String> paramMap = new HashMap<String, String>();
String result = HttpClientUtil.sendPost(stockUrl, paramMap, param);
	public static String sendPost(String url, Map<String, String> headers, String data) {
		String response = null;
		try {
			CloseableHttpClient httpclient = null;
			CloseableHttpResponse httpresponse = null;
			SSLContext ctx = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
				// 信任所有
				public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					return true;
				}
			}).build();
			try {
				SSLConnectionSocketFactory fac = new SSLConnectionSocketFactory(ctx, new String[] { "TLSv1.2" },null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
				httpclient = HttpClientBuilder.create().setSSLSocketFactory(fac).build();
				HttpPost httppost = new HttpPost(url);
				StringEntity stringentity = new StringEntity(data, ContentType.create("application/json", "UTF-8"));
				httppost.setEntity(stringentity);
				// 循环添加header
				Iterator headerIterator = headers.entrySet().iterator();
				while (headerIterator.hasNext()) {
					Entry<String, String> elem = (Entry<String, String>) headerIterator.next();
					httppost.addHeader(elem.getKey(), elem.getValue());
				}
				//发post请求
				httpresponse = httpclient.execute(httppost);
				//utf-8参数防止中文乱码
				response = EntityUtils.toString(httpresponse.getEntity(), "utf-8");
			} finally {
				if (httpclient != null) {
					httpclient.close();
				}
				if (httpresponse != null) {
					httpresponse.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐