java 发起rest请求_JAVA发HTTP请求 - RestTemplate 案例

一、对比

java发送Http post请求,一般在java中我们使用 httpcilent 包中的额 HttpPost 类;需要手动设置 setContentType 和 setContentEncoding;

代码书写看起来非常low 如下代码所示,而 spring 提供的 RestTemplate 提供的额方法则看起来就比较高大上一点:

public static String httpPostWithjson(String url, String json) throws IOException

{

String result = "";

HttpPost httpPost = new HttpPost(url);

CloseableHttpClient httpClient = HttpClients.createDefault();

try

{

BasicResponseHandler handler = new BasicResponseHandler();

StringEntity entity = new StringEntity(json, "utf-8"); //解决中文乱码问题

entity.setContentEncoding("UTF-8");

entity.setContentType("application/json");

httpPost.setEntity(entity);

result = httpClient.execute(httpPost, handler);

return result;

}

catch(Exception e)

{

e.printStackTrace();

}

finally

{

try

{

httpClient.close();

}

catch(Exception e)

{

e.printStackTrace();

}

}

return result;

}

二、话不多说,直接给2个常用 RestTemplate 案例,复制即可使用:

提交JSON格式的数据

public class Test

{

private static RestTemplate restTemplate = new RestTemplate();

public static String sendHttpRequestStatic(String url, JSONObject jsonParam)

{

JSONObject result = new JSONObject();

try

{

HttpHeaders httpHeaders = new HttpHeaders();

httpHeaders.setContentType(MediaType.APPLICATION_JSON);

HttpEntity < String > request = new HttpEntity < > (jsonParam.toJSONString(), httpHeaders);

ResponseEntity < String > response = restTemplate.postForEntity(url, request, String.class);

// Http 请求成功返回响应体

if(response.getStatusCodeValue() == 200)

{

String resultStr = JSON.toJSONString(response.getBody()).replace("\\", "");

return resultStr.substring(1, resultStr.length() - 1);

}

else

{

result.put("code", "-1");

result.put("data", "请求失败");

return result.toJSONString();

}

}

catch(Exception e)

{

e.printStackTrace();

result.put("code", "-1");

result.put("data", "请求异常");

return result.toJSONString();

}

}

}

提交表单数据(multipart/form-data)

public String sendHttpRequest(String url, JSONObject jsonParam, Map < String, String > param)

{

JSONObject result = new JSONObject();

try

{

String body;

HttpHeaders httpHeaders = new HttpHeaders();

httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);

MultiValueMap < String, String > mapParam = new LinkedMultiValueMap < > ();

mapParam.setAll(param);

HttpEntity < MultiValueMap < String, String >> request = new HttpEntity < > (mapParam, httpHeaders);

RestTemplate restTemplate = new RestTemplate();

ResponseEntity < String > response = restTemplate.exchange(url, HttpMethod.POST, request, String.class);

// Http 请求成功返回响应体

if(response.getStatusCodeValue() == 200)

{

String resultStr = JSON.toJSONString(response.getBody()).replace("\\","");

return resultStr.substring(1, resultStr.length() - 1);

}

else

{

result.put("code", "-1");

result.put("data", "请求失败");

return result.toJSONString();

}

}

catch(Exception e)

{

e.printStackTrace();

result.put("code", "-1");

result.put("data", "请求异常");

return result.toJSONString();

}

}

看起来代码是不是高大上一点,当然RestTemplate还有许多其他调用方式,需要的朋友可以查看一下:其他方式

赞(3)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java RestTemplate 是 Spring Framework 提供的一个用于访问 REST 服务的客户端工具类。它简化了与 RESTful Web 服务的通信,可以送 GET、POST、PUT、DELETE 请求等,并支持通过多种方式传递参数和请求体。使用 RestTemplate 送 HTTP 请求时,可以使用 Spring 提供的 MessageConverter 将请求和响应转换为相应的 Java 对象,从而方便处理返回的 JSON/XML 数据。 RestTemplate 的使用非常简单,只需要实例化一个 RestTemplate 对象,然后使用该对象的方法来请求即可。例如,可以使用 RestTemplate 的 getForObject() 方法送 GET 请求并返回响应体: ```java RestTemplate restTemplate = new RestTemplate(); String url = "http://example.com/api/resource"; String response = restTemplate.getForObject(url, String.class); ``` 除了 getForObject() 方法,还有 postForObject()、put()、delete() 等方法可供使用。 如果需要传递参数,可以将参数封装为一个 Map 对象,然后将其传递给方法。例如,可以使用 RestTemplate 的 postForObject() 方法送 POST 请求并传递参数: ```java RestTemplate restTemplate = new RestTemplate(); String url = "http://example.com/api/resource"; MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add("param1", "value1"); params.add("param2", "value2"); String response = restTemplate.postForObject(url, params, String.class); ``` 以上就是 Java RestTemplate 的基本介绍和使用方法。如有需要,可以参考 Spring 官方文档进一步了解该工具类的更多特性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值