软件编程
位置:首页>> 软件编程>> java编程>> Java实现调用对方http接口得到返回数据

Java实现调用对方http接口得到返回数据

作者:peachlf  发布时间:2023-02-27 22:36:29 

标签:Java,http接口,返回数据

Java 用对方http接口得到返回数据

如图所示我们这里自己写一个接口作为访问地址,返回的是json字符串

Java实现调用对方http接口得到返回数据

首先我们在浏览器访问这个接口的地址,会在浏览器打印出如图所示的内容,

Java实现调用对方http接口得到返回数据

然后我们写一个方法访问刚刚的接口地址,使用HttpURLConnextion进行访问,通过BufferedReader获取流,已得到返回的值

Java实现调用对方http接口得到返回数据

运行这个方法,会在控制台打印出接口返回的值,也可以进行相应的操作

Java实现调用对方http接口得到返回数据

如图所示是第二种方法,通过URL进行连接,然后通过openStream方法获取返回值的流转为BufferedReader,然后进行相应的操作

Java实现调用对方http接口得到返回数据

接着赋值url接口地址后,运行后结果如图所示,这里还可以使用jsonfrom等方法对获取的返回值进行json解析,以更方便操作

Java实现调用对方http接口得到返回数据

java后台工具类调用api接口,解析数据

httpclient后台调用接口,解析数据

一 、 引入jar包


       <dependency>
           <groupId>org.apache.httpcomponents</groupId>
           <artifactId>httpclient</artifactId>
           <version>4.5.3</version>
       </dependency>
        <!-- JSON转换包 -->
       <dependency>
           <groupId>net.sf.json-lib</groupId>
           <artifactId>json-lib</artifactId>
           <version>2.4</version>
           <classifier>jdk15</classifier>
       </dependency>

二、 httpclient请求接口工具类

2.1 get、post、“head”, “options”, “delete”, "trace"等方式


public class HttpClient {
   /**
    * 向目的URL发送post请求
    *
    * @param url          目的url
    * @param headerParams 请求头参数 key:value
    * @param bodyParams   请求体参数  key:value
    * @return
    */
   public static String sendPostRequest(String url, Map<String, String> headerParams,
                                        Map<String, String> bodyParams) {
       RestTemplate client = new RestTemplate();
       //新建Http头,add方法可以添加参数
       HttpHeaders headers = new HttpHeaders();
       //给请求头设置参数
       for (String key : headerParams.keySet()) {
           headers.add(key, headerParams.get(key));
       }
       //设置请求发送方式HttpMethod.GET、HttpMethod.DELETE等
       HttpMethod method = HttpMethod.POST;
       // 设置提交方式这里设置成application/json格式
       headers.setContentType(MediaType.APPLICATION_JSON);
       //将请求头部和参数合成一个请求
       HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(bodyParams, headers);
       //执行HTTP请求,将返回的结构使用String 类格式化(可设置为对应返回值格式的类)
       ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
       //返回类型也可以自动填充到实体类当中去,比如我自己创建了User类,当然字段名称要和返回字段一致
       //ResponseEntity<User> response = client.exchange(url, method, requestEntity, User.class);
       return response.getBody();
   }

2.2 PATCH等其他方式


/**
    * 向目的URL发送patch请求,只比其他方式多了一个允许aptch方式的方法。
    * 由于httpclient不支持patch请求,所以需要反射方式获取连接对象,增加patch方式
    * @param url          目的url
    * @param headerParams 请求头参数
    * @param bodyParams   请求体参数
    * @return AdToutiaoJsonTokenData
    */
   public static String sendPatchRequest(String url, Map<String, String> headerParams,
                                         Map<String, String> bodyParams) {
       //httpclient不支持patch请求,反射方式获取连接对象,增加patch方式
       allowMethods("PATCH");
       RestTemplate client = new RestTemplate();
       //新建Http头,add方法可以添加参数
       HttpHeaders headers = new HttpHeaders();
       //给请求头设置参数
       for (String key : headerParams.keySet()) {
           headers.add(key, headerParams.get(key));
       }
       //headers.add("X-HTTP-Method-Override", "PATCH");
       //设置请求发送方式
       HttpMethod method = HttpMethod.PATCH;
       // 设置提交方式这里设置成application/json格式
       headers.setContentType(MediaType.APPLICATION_JSON);
       //将请求头部和参数合成一个请求
       HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(bodyParams, headers);
       //执行HTTP请求,将返回的结构使用String 类格式化(可设置为对应返回值格式的类)
       ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
       return response.getBody();
   }
   //增加支持patch请求方式
   private static void allowMethods(String... methods) {
       try {
        //获取连接类的属性,给属性添加aptch就允许aptch请求方式了
           Field methodsField = HttpURLConnection.class.getDeclaredField("methods");
           Field modifiersField = Field.class.getDeclaredField("modifiers");
           modifiersField.setAccessible(true);
           modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL);
           methodsField.setAccessible(true);
           String[] oldMethods = (String[]) methodsField.get(null);
           Set<String> methodsSet = new LinkedHashSet<>(Arrays.asList(oldMethods));
           methodsSet.addAll(Arrays.asList(methods));
           String[] newMethods = methodsSet.toArray(new String[0]);
           methodsField.set(null/*static field*/, newMethods);
       } catch (NoSuchFieldException | IllegalAccessException e) {
           throw new IllegalStateException(e);
       }
   }

2.3 解析数据


//工具类调用api接口,获取返回数据
String result = HttpClient.sendPostRequest(createZoomMeetingUrl,header,body);
       JSONObject json = JSONObject.fromObject(result);
       //解析获取数据
       String startUrl = json.getString("start_url");
       String joinUrl = json.getString("join_url");
       //会议室id
       int id = json.getInt("id");
       //解析数据数据
       JSONArray jsonArray = json.getJSONArray("users");
       for(int i=0;i<jsonArray .size();i++){
         String firstName = jsonArray.getJSONObject(i).getString("first_name");
         ...............
       }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

来源:https://www.cnblogs.com/peachh/p/13658125.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com