java实现Http请求

版权声明:未经允许,不得转载 https://blog.csdn.net/dhj199181/article/details/83617077

以下代码是本人在实际工作中总结出来的,个人感觉还是比较精简干练的,

get请求:


	public static String getMethod(String url,Map<String,Object> dataMap) throws  Exception{
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		try {
			httpClient = HttpClients.createDefault();
			//封装请求参数
			List<NameValuePair> params = Lists.newArrayList();
			for (Entry<String, Object> entry: dataMap.entrySet()) {
				params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
			}
			String str = EntityUtils.toString(new UrlEncodedFormEntity(params, Consts.UTF_8));
			//创建Get请求
			HttpGet httpGet = new HttpGet(url+"?"+str);
			//超时设置
			RequestConfig requestConfig = RequestConfig.custom()
			        .setConnectTimeout(5000)
			        .setConnectionRequestTimeout(1000)
			        .setSocketTimeout(5000)
			        .build();
			httpGet.setConfig(requestConfig);
			//执行Get请求,
			response = httpClient.execute(httpGet);
			//得到响应体
            return EntityUtils.toString(response.getEntity(), Consts.UTF_8); 
		}finally{
			//消耗实体内容
			close(response);
			//关闭相应 丢弃http连接
			close(httpClient);
		}
	}

post请求

public static String postMethod(String url,Map<String,Object> dataMap) throws  Exception{
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		try {
			httpClient = HttpClients.createDefault();
			//封装请求参数
			String params = JSONObject.toJSONString(dataMap);
			System.out.println(url+"?"+params);
			//创建post请求
			HttpPost httpPost = new HttpPost(url);
			//执行post请求,
			httpPost.addHeader("Content-Type", "application/json");
			//设置超时
			RequestConfig requestConfig = RequestConfig.custom()
				        .setConnectTimeout(5000)
				        .setConnectionRequestTimeout(1000)
				        .setSocketTimeout(5000).build();
			httpPost.setConfig(requestConfig);
			HttpEntity reqEntity = new StringEntity(params, Consts.UTF_8);
			httpPost.setEntity(reqEntity);
			response = httpClient.execute(httpPost);
            //得到响应体
            return EntityUtils.toString(response.getEntity(), Consts.UTF_8); 
		}finally{
			//消耗实体内容
			close(response);
			//关闭相应 丢弃http连接
			close(httpClient);
		}
	}

关闭流

	private static void close(Closeable closable){
		//关闭输入流,释放资源
		if(closable != null){
			try {
				closable.close();
			} catch (IOException e) {
				log.error("IO流关闭异常",e);
			}
		}
	}

猜你喜欢

转载自blog.csdn.net/dhj199181/article/details/83617077