使用Java调用RestFul接口,以POST请求为例,以下提供几种方法:

一、通过HttpURLConnection调用

 1 public String postRequest(String url, String param) {
2 StringBuffer result = new StringBuffer();
3
4 HttpURLConnection conn = null;
5 OutputStream out = null;
6 BufferedReader reader = null;
7 try {
8 URL restUrl = new URL(url);
9 conn = (HttpURLConnection) restUrl.openConnection();
10 conn.setRequestMethod("POST");
11 conn.setDoOutput(true);
12 conn.setDoInput(true);
13
14 conn.setRequestProperty("accept", "*/*");
15 conn.setRequestProperty("connection", "Keep-Alive");
16 conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
17 conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
18
19 conn.connect();
20 out = conn.getOutputStream();
21 out.write(param.getBytes());
22 out.flush();
23
24 int responseCode = conn.getResponseCode();
25 if(responseCode != 200){
26 throw new RuntimeException("Error responseCode:" + responseCode);
27 }
28
29 String output = null;
30 reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
31 while((output=reader.readLine()) != null){
32 result.append(output);
33 }
34 } catch (Exception e) {
35 e.printStackTrace();
36 throw new RuntimeException("调用接口出错:param+"+param);
37 } finally {
38 try {
39 if(reader != null){
40 reader.close();
41 }
42 if(out != null){
43 out.close();
44 }
45 if(conn != null){
46 conn.disconnect();
47 }
48 } catch (Exception e2) {
49 e2.printStackTrace();
50 }
51 }
52
53 return result.toString();
54 }

二、通过Spring提供的RestTemplate模板调用

 1 public class RestTemplateUtil {
2
3 @Autowired
4 private RestTemplate restTemplate;
5
6 @Bean
7 public RestTemplate restTemplate(){
8 RestTemplate template = new RestTemplate();
9 // messageConverters是RestTemplate的一个final修饰的List类型的成员变量
10 // messageConverters的第二个元素存储的是StringHttpMessageConverter类型的消息转换器
11 // StringHttpMessageConverter的默认字符集是ISO-8859-1,在此处设置utf-8字符集避免产生乱码
12 template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("utf-8")));
13 return template;
14 }
15
16 public String post(String url, String jsonParam){
17 // 自定义请求头
18 HttpHeaders headers = new HttpHeaders();
19 headers.setContentType(MediaType.APPLICATION_JSON);
20 headers.setAcceptCharset(Collections.singletonList(Charset.forName("utf-8")));
21 headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
22
23 // 参数
24 HttpEntity<String> entity = new HttpEntity<String>(jsonParam, headers);
25 // POST方式请求
26 ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
27 if(responseEntity == null){
28 return null;
29 }
30
31 return responseEntity.getBody().toString();
32 }
33
34 }

三、通过HttpClient调用

 1 public class HttpClientUtil {
2
3 public String post(String url, Map<String, Object> pramMap) throws Exception {
4 String result = null;
5 // DefaultHttpClient已过时,使用CloseableHttpClient替代
6 CloseableHttpClient closeableHttpClient = null;
7 CloseableHttpResponse response = null;
8 try {
9 closeableHttpClient = HttpClients.createDefault();
10 HttpPost postRequest = new HttpPost(url);
11 List<NameValuePair> pairs = new ArrayList<>();
12 if(pramMap!=null && pramMap.size() > 0){
13 for (Map.Entry<String, Object> entry : pramMap.entrySet()) {
14 pairs.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
15 }
16 }
17 UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairs, "utf-8");
18 postRequest.setEntity(formEntity);
19
20 response = closeableHttpClient.execute(postRequest);
21 if(response!=null && response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
22 result = EntityUtils.toString(response.getEntity(), "utf-8");
23 }else{
24 throw new Exception("post请求失败,url" + url);
25 }
26
27 } catch (Exception e) {
28 e.printStackTrace();
29 throw e;
30 } finally {
31 try {
32 if(response != null){
33 response.close();
34 }
35 if(closeableHttpClient != null){
36 closeableHttpClient.close();
37 }
38 } catch (IOException e) {
39 e.printStackTrace();
40 }
41 }
42
43 return result;
44 }
45
46 }

Java调用RestFul接口的更多相关文章

  1. 三种方法实现java调用Restful接口

    1,基本介绍 Restful接口的调用,前端一般使用ajax调用,后端可以使用的方法比较多, 本次介绍三种: 1.HttpURLConnection实现 2.HttpClient实现 3.Spring ...

  2. java调用restful接口的方法

    Restful接口的调用,前端一般使用ajax调用,后端可以使用的方法如下: 1.HttpURLConnection实现 2.HttpClient实现 3.Spring的RestTemplate

  3. Java 调用Restful API接口的几种方式--HTTPS

    摘要:最近有一个需求,为客户提供一些Restful API 接口,QA使用postman进行测试,但是postman的测试接口与java调用的相似但并不相同,于是想自己写一个程序去测试Restful ...

  4. 三种方法实现调用Restful接口

    1.基本介绍 Restful接口的调用,前端一般使用ajax调用,后端可以使用的方法比较多, 本次介绍三种: 1.HttpURLConnection实现 2.HttpClient实现 3.Spring ...

  5. Java调用webservice接口方法

                             java调用webservice接口   webservice的 发布一般都是使用WSDL(web service descriptive langu ...

  6. python 调用RESTFul接口

    本周需要将爬虫爬下来的数据入库,因为之前已经写好PHP的接口的,可以直接通过python调用PHP接口来实现,所以把方法总结一下. //python编码问题,因为好久用,所以很容易出现 # -*- c ...

  7. Java 调用http接口(基于OkHttp的Http工具类方法示例)

    目录 Java 调用http接口(基于OkHttp的Http工具类方法示例) OkHttp3 MAVEN依赖 Http get操作示例 Http Post操作示例 Http 超时控制 工具类示例 Ja ...

  8. (二)通过JAVA调用SAP接口 (增加一二级参数)

    (二)通过JAVA调用SAP接口 (增加一二级参数) 一.建立sap连接 请参考我的上一篇博客 JAVA连接SAP 二.测试项目环境准备 在上一篇操作下已经建好的环境后,在上面的基础上新增类即可 三. ...

  9. Java方法通过RestTemplate调用restful接口

    背景:项目A需要在代码内部调用项目B的一个restful接口,该接口是POST方式,header中 Authorization为自定义内容,主要传输的内容封装在body中,所以使用到了RestTemp ...

随机推荐

  1. SM4

    整体结构 T变换 SM4解密的合理性证明 秘钥扩展

  2. C# 使用 log4net 日志组件

    一. 什么是 log4net  Apache log4net 库是帮助程序员将日志语句输出到各种输出目标的工具,它是从Java中的Log4j迁移过来的一个.Net版的开源日志框架.log4net 的一 ...

  3. docker配置mysql实现主从同步问题

    主从同步遇到 Got fatal error 1236 from master when reading data from binary log: 'Could not find first log ...

  4. webservcie学习之webservice是什么

    之前写代码,只是用到的时候才去看相关技术,用过后也没有再回头特别 去看,现在突然发现对一些技术的了解不够深刻,故现在准备再从头对用到的技术深入的学习下.就从webservice开始.首先对我不解的地方 ...

  5. 在.NET Core中使用Channel(一)

    我最近一直在熟悉.net Core中引入的新Channel<T>类型.我想在它第一次发布的时候我了解过它,但是有关文章非常非常少,我不能理解它们与其他队列有什么不同. 在使用了一段时间后, ...

  6. spark知识点_RDD

    来自官网的Spark Programming Guide,包括个人理解的东西. 这里有一个疑惑点,pyspark是否支持Python内置函数(list.tuple.dictionary相关操作)?思考 ...

  7. mysql修改sql_mode为宽松模式

    sql_mode ANSI TRADITIONAL STRICT_TRANS_TABLES sql_mode为空 最宽松的模式, 即使有错误既不会报错也不会有警告️ ANSI 宽松模式,对插入数据进行 ...

  8. ASP.NET Core 3.1 中间件

    参考微软官方文档 : https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.1 ...

  9. Es5数组新增的方法及用法

    1.forEachforEach是Array新方法中最基本的一个,就是遍历,循环.例如下面这个例子: [1, 2 ,3, 4].forEach(alert);等同于下面这个传统的for循环: var ...

  10. SQL LEN()函数用法

    含义: LEN 函数返回文本字段中值的长度. 返回字符表达式中的字符数 SQL LEN() 语法 SELECT LEN(column_name) FROM table_name 举例: 1.LEN对相 ...