天天看點

HTTP調用遠端接口-java

HTTP調用遠端接口-java

一、url帶參

String path = https://www.***.com/api/getToken?userId=123

CloseableHttpClient httpClient = HttpClients.createDefault();
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    try {
        httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(path);
        httpGet.setHeader("Content-type", "application/json");
        //擷取傳回值
        String execute = httpClient.execute(httpGet, responseHandler);
        log.info("execute ="+execute );
    }catch (Exception e){
        throw new RRException("調用接口失敗");
    }
           

二、參數轉成JSON字元串

String path = https://www.***.com/api/getToken

String json="{“name”:“張三”,“mobile”:123}\n";

CloseableHttpClient httpClient = HttpClients.createDefault();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try {
            httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(path);
            //給httpPost設定JSON格式的參數
            StringEntity requestEntity = new StringEntity(json,"utf-8");
            requestEntity.setContentEncoding("UTF-8");
            httpPost .setHeader("Content-type", "application/json");
            httpPost.setEntity(requestEntity);
            String execute = httpClient.execute(httpPost , responseHandler);
            //解析為Map
            Map<String,Object> params = (Map<String,Object>)   JSON.parse(execute);
            log.info(params);
        }catch (Exception e){
            throw new RRException("調用接口失敗");
        }
           

三、請求頭中帶參

String path = https://www.***.com/api/getToken

CloseableHttpClient httpClient = HttpClients.createDefault();
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    try {
        httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(path);
        httpGet.setHeader("Content-type", "application/json");
        //=======往請求頭中放入參數======
        httpGet.setHeader("type", "123");
        httpGet.setHeader("page", "10");
        //=======往請求頭中放入參數END======
        //擷取傳回值
        String execute = httpClient.execute(httpGet, responseHandler);
        log.info("execute ="+execute );
    }catch (Exception e){
        throw new RRException("調用接口失敗");
    }
           

解析請求頭資料:https://blog.csdn.net/xiaotianshi_01/article/details/108072095