http的post请求

private String valueOf(String url, String param,String token) throws IOException {
        String result;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response;
        HttpPost httpPost = new HttpPost(url);
        if(null != token && token.length() > 0){
            httpPost.setHeader("token", token);
        }
        //配置ResquestConfig
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000)
                .setConnectTimeout(15000)
                .setConnectionRequestTimeout(15000)
                .build();
        //配置StringEntity
        StringEntity stringEntity = new StringEntity(String.valueOf(param), "UTF-8");
        stringEntity.setContentType("application/json");

        //将Entity和Config设置到HttpPost
        httpPost.setEntity(stringEntity);
        httpPost.setConfig(requestConfig);
        //获取页面
        response = httpClient.execute(httpPost);
        result = EntityUtils.toString(response.getEntity(), "UTF-8");
        return result;
    }
String data = this.getAllDevice("这里是url",token);

private String getAllDevice(String url, String param) throws IOException {
        String result;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response;
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("token", param);
        //配置ResquestConfig
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000)
                .setConnectTimeout(15000)
                .setConnectionRequestTimeout(15000)
                .build();
        //配置StringEntity
        StringEntity stringEntity = new StringEntity(String.valueOf(param), "UTF-8");
        stringEntity.setContentType("application/json");

        //将Entity和Config设置到HttpPost
        httpPost.setEntity(stringEntity);
        httpPost.setConfig(requestConfig);
        //获取页面
        response = httpClient.execute(httpPost);
        result = EntityUtils.toString(response.getEntity(), "UTF-8");
        JSONObject jsonobject = JSONObject.parseObject(result);
        String data = jsonobject.getString("data");
        return data;
    }

你可能感兴趣的:(java)