首页 > 技术文章 > httpClient POST 请求

lxnv587 2019-03-08 14:56 原文

/**
	 * http post请求
	 * @param url
	 * @param map
	 * @return
	 */
	public static JSONObject doPostByMap(String url,Map<String, String> map) {
		
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			
			// 设置超时时间
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();//设置请求和传输超时时间
			httpPost.setConfig(requestConfig);
			
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			if (map != null) {
				for (Entry<String, String> entry : map.entrySet()) {
					nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
				}
			}
			// 设置参数到请求对象中
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

			// 执行http请求
			response = httpClient.execute(httpPost);

			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return returnJson(resultString);
	}


/**
	 * 将返回值转换成JSON对象
	 * 
	 * @param str
	 * @return
	 */
	private static JSONObject returnJson(String str) {
		String[] strs = str.split("&");
		Map map = new HashMap();
		for (String s : strs) {
			String[] s1 = s.split("=");
			JSONArray js = JSONArray.fromObject(s1);
			if (js.size() > 1) {
				String key = (String) js.get(0);
				String value = (String) js.get(1);
				map.put(key, value);
			}
		}
		return JSONObject.fromObject(map);
	}

  

推荐阅读