commons-httpcomponents

这组包下面主要定义处理http相关请求的类(异步与同步):

一、httpclient:

        <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>                
         </dependency>
package org.eclipse.winery.repository;

import java.nio.charset.Charset;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.google.gson.Gson;

public class App1 {

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        String apiurl = "http://127.0.0.1:8080/index.txt";
        String body = null;
        HttpClient httpClient = HttpClients.createDefault();//创建httpclient
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000)
                .setSocketTimeout(5000).build();//超时时间配置
        HttpPost method = new HttpPost(apiurl);
        method.setConfig(requestConfig);//设置超时时间
        method.addHeader("Content-type", "application/json; charset=utf-8");//设置请求头
        method.setHeader("Accept", "application/json");//设置请求头
        method.setEntity(new StringEntity(new Gson().toJson(new EntityObj()), Charset.forName("UTF-8")));//设置请求体
        HttpResponse response = httpClient.execute(method);//执行请求
        int statusCode = response.getStatusLine().getStatusCode();//获取返回码
        if (statusCode == HttpStatus.SC_OK) {
            body = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));//获取返回体
            System.out.println("statusCode: " + statusCode);
            System.out.println("body: " + body);
        }
    }

    private static class EntityObj {
        private String id = "EntityObjId";
        private String name = "EntityObjName";

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

}
原文地址:https://www.cnblogs.com/erdanyang/p/10167683.html