利用HttpClient4,实现get,post 参数,post json,post file

JAVA httpclient 请求最佳实现

以下会依次列举常见的几种请求类型 : get , post param , post json , post file

GET

/**
 * get类型的
 * 
 * @param url
 * @throws ClientProtocolException
 * @throws IOException
 */
public static void testGet(String url) throws ClientProtocolException, IOException {
    // 设置超时时间,单位是秒
    RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000)
            .setConnectionRequestTimeout(3000).build();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpGet httpget = new HttpGet(url);
        httpget.setConfig(defaultRequestConfig);
        ResponseHandler responseHandler = new ResponseHandler() {
            public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }
        };

        String responseBody = httpclient.execute(httpget, responseHandler);
        System.out.println(responseBody);
    } finally {
        httpclient.close();
    }
}

POST 参数

/**
 * form类型的,传参数
 * 
 * @param url
 * @param map 参数
 * @throws ClientProtocolException
 * @throws IOException
 */
public static void testPostParam(String url,Map map) throws ClientProtocolException, IOException {
    // 设置超时时间
    RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000)
            .setConnectionRequestTimeout(3000).build();

    CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
    httpClient = HttpClients.createDefault();

    HttpPost post = new HttpPost("http://httpbin.org/post");

    post.setConfig(defaultRequestConfig);

    // 传参数
    List list = new ArrayList();
    for(Entry entry: map.entrySet()){
        list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    }
    HttpEntity ent = new UrlEncodedFormEntity(list, "UTF-8");
    post.setEntity(ent);

    ResponseHandler responseHandler = new ResponseHandler() {
        public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            int status = response.getStatusLine().getStatusCode();
            System.out.println(response.getEntity().toString());
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        }
    };

    System.out.println(httpClient.execute(post, responseHandler));
}

POST JSON

/**
 * post json
 * 
 * @param url 请求地址
 * @param jsonStr 请求json字符串
 * @throws ClientProtocolException
 * @throws IOException
 */
public static void testPostJson(String url,String jsonStr) throws ClientProtocolException, IOException {
    // 设置超时时间
    RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000)
            .setConnectionRequestTimeout(3000).build();

    CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
    httpClient = HttpClients.createDefault();

    HttpPost post = new HttpPost(url);

    post.setConfig(defaultRequestConfig);

    // 传json字符串 "{\"key\":\"value\"}"
    StringEntity stringEntity = new StringEntity(jsonStr);
    stringEntity.setContentType("text/json");
    stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    post.setEntity(stringEntity);

    ResponseHandler responseHandler = new ResponseHandler() {
        public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        }
    };

    System.out.println(httpClient.execute(post, responseHandler));
}

POST FILE

/**
 * 上传文件
 * @param url 上传接口地址
 * @param filePath
 * @param fileName
 * @throws ClientProtocolException
 * @throws IOException
 */
public static void testPostFile(String url,String filePath,string fileName) throws ClientProtocolException, IOException {
    RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(3000)
            .setConnectionRequestTimeout(3000).build();

    CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
    httpClient = HttpClients.createDefault();

    HttpPost post = new HttpPost(url);
    // 设置超时时间
    post.setConfig(defaultRequestConfig);

    // 传文件
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addTextBody("name", "test");

    builder.addBinaryBody("file", new File(filePath), ContentType.DEFAULT_BINARY,
            fileName);
    post.setEntity(builder.build());

    ResponseHandler responseHandler = new ResponseHandler() {
        public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        }
    };

    System.out.println(httpClient.execute(post, responseHandler));
}

你可能感兴趣的:(java)