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
    评论
Java中,有多种方式可以实现HTTP请求。其中一种常见的方式是使用Java标准库中的HttpURLConnection类。这个类提供了发送HTTP请求和接收HTTP响应的功能。你可以使用HttpURLConnection类创建连接,并设置请求方法、请求头、请求体等,然后发送请求并获取响应。具体的代码可以参考以下示例: ``` import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class HttpExample { public static void main(String[] args) throws IOException { URL url = new URL("https://www.example.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); // 设置请求方法,例如GET、POST等 connection.setConnectTimeout(5000); // 设置连接超时时间 connection.setReadTimeout(5000); // 设置读取超时时间 int responseCode = connection.getResponseCode(); // 获取响应码 if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = connection.getInputStream(); // 处理响应数据 } else { // 处理错误情况 } connection.disconnect(); // 断开连接 } } ``` 另外,你还可以使用第三方库来简化HTTP请求的过程,比如OkHttp和Spring的RestTemplate。使用OkHttp时,你可以创建一个OkHttpClient实例,并使用Request类来构建请求,然后发送请求并获取响应。以下是一个使用OkHttp的示例代码: ``` import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import java.io.IOException; public class OkHttpExample { private static final OkHttpClient client = new OkHttpClient(); public static void main(String[] args) throws IOException { Request request = new Request.Builder() .url("https://www.example.com") .build(); try (Response response = client.newCall(request).execute()) { String result = response.body().string(); System.out.println(result); } } } ``` 如果你使用Spring框架,你可以使用RestTemplate类来发送HTTP请求。RestTemplate封装了HTTP请求的各种方法,让你可以更方便地发送请求和处理响应。以下是一个使用RestTemplate的示例代码: ``` import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; public class RestTemplateExample { public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate.getForEntity("https://www.example.com", String.class); String result = response.getBody(); System.out.println(result); } } ``` 以上是三种常见的Java实现HTTP请求的方法,你可以根据具体的需求选择适合的方式来发送HTTP请求。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Java 实现HTTP请求的四种方式总结](https://blog.csdn.net/qq_34383510/article/details/130627924)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值