java实现Http请求

2 篇文章 0 订阅

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

get请求key=value格式报文


	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请求json格式报文

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);
			}
		}
	}

post请求key=value格式报文

/**
	 * 参数key=value形式

	 */
	public static String postMethod(String url,Map<String,Object> dataMap) throws  Exception{
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		try {
			   httpClient = HttpClients.createDefault();
               HttpPost post = new HttpPost(url);
               //requestConfig post请求配置类,设置超时时间
   			   RequestConfig requestConfig = RequestConfig.custom()
   				        .setConnectTimeout(5000)
   				        .setConnectionRequestTimeout(3000)
   				        .setSocketTimeout(5000).build();
               post.setConfig(requestConfig);
               List<NameValuePair> params = new ArrayList<>();
               for (Entry<String, Object> entry: dataMap.entrySet()) {
   					params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
   				}
               //在这个地方设置编码 防止请求乱码
               post.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
               response = httpClient.execute(post);
               //响应结果
               return EntityUtils.toString(response.getEntity(), Consts.UTF_8); 
          }finally{
        	//消耗实体内容
  			IOUtils.closeQuietly(response);
  			//关闭相应 丢弃http连接
  			IOUtils.closeQuietly(httpClient);
          }
	}
	

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值