java-常用-后台调用接口

依赖的jar包

      <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version>
        </dependency>
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>

GET请求

@Test
public void test1() {
    //get
    HttpClient client = new HttpClient();
    String url = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13800000004";
    GetMethod getMethod = new GetMethod(url);
    try {
        int i = client.executeMethod(getMethod);
        if (i == 200) {
            String res = getMethod.getResponseBodyAsString();
            System.out.println(res);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

POST请求

@Test
    public void test2() throws Exception {
        //POST
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost httpPost = new HttpPost("https://emall.dlg-property.com/api/Wxapps/getProducts");
     //参数
        String s = "{\"device_id\":\"TN11204340776\"}";
        StringEntity t = new StringEntity(s, "utf-8");
        t.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                "application/json"));
        //设置参数到请求对象中
        httpPost.setEntity(t);
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");

        CloseableHttpResponse response = null;
        response = httpClient.execute(httpPost);
        
        if (response != null && response.getStatusLine().getStatusCode() == 200) {
        
            HttpEntity responseEntity = response.getEntity();
            String jsonStr = EntityUtils.toString(responseEntity, "UTF-8");
            System.out.println(jsonStr);//JSON对象
        //操作json对象
            JSONObject jsStr = JSONObject.parseObject(jsonStr);
            JSONObject data=jsStr.getJSONObject("data");

            ResInfo resInfo = JSONObject.parseObject(data.toJSONString(), ResInfo.class);
            System.out.println(resInfo.getMessage());
        }

    }

详见

https://blog.csdn.net/lc545126483/article/details/88941365

posted @ 2020-07-08 11:07  雨后星辰zxj  阅读(250)  评论(0编辑  收藏  举报