zoukankan      html  css  js  c++  java
  • 使用httpClient调用接口获取响应数据

    转自:https://blog.csdn.net/shuaishuaidewo/article/details/81136088
    import lombok.extern.slf4j.Slf4j;
    import okhttp3.*;
    
    /**
     * 需要注入依赖
     *  <dependency>
    *         <groupId>com.squareup.okhttp3</groupId>
     *        <artifactId>okhttp</artifactId>
     *        <version>3.6.0</version>
     *  </dependency>
     */
    @Slf4j
    public class HttpClientUtils {
    
        public static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");
    
        /**
         * get请求获取请求数据
         * @param url
         * @return
         */
        public static String httpGet(String url){
            String getData ;
            OkHttpClient httpClient = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            try {
                Response response = httpClient.newCall(request).execute();
                getData = response.body().string();
    
            }catch (Exception e){
                log.info("【发送 GET 请求出现异常】!" + e.getMessage());
                return "-1";
            }
            return getData;
        }
    
    
        /**
         * post请求获取请求数据
         * @param url
         * @param json
         * json数据的生成方式(可选);
         *      JSONObject json=new JSONObject();
         *      json.put("name","张三");
         *      json.put("sex","男");等
         *      json.toString()
         * @return
         */
        public static String httpPost(String url, String json){
            String postData ;
            OkHttpClient httpClient = new OkHttpClient();
            RequestBody requestBody = RequestBody.create(JSON, json);
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();
            try {
                Response response = httpClient.newCall(request).execute();
                postData = response.body().string();
            }catch (Exception e){
                log.info("【发送 POST 请求出现异常】!" + e.getMessage());
                return "-1";
            }
            return postData;
        }
    
        public static void main(String[] args) {
            String loadJSON = httpGet("https://vhouyun.com/goods/RankGoodsList?day=yesterday&role=3");
            System.out.println(loadJSON);
            //post方式请求自己测试即可
        }
    
    }
  • 相关阅读:
    selector 使用说明
    volley用法之 以post方式发送 json 参数
    linux系统下使用流行的版本管理工具 Git
    Android BLE 蓝牙编程(四)
    Android BLE 蓝牙编程(三)
    Android BLE 蓝牙编程(二)
    Android BLE 蓝牙编程(一)
    php比较两个字符串是否相同
    下拉刷新
    理财小工具(二)贷款计算器
  • 原文地址:https://www.cnblogs.com/yadongliang/p/9665532.html
Copyright © 2011-2022 走看看