• 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;
            }
        }
    
    }
  • 相关阅读:
    UML中对关系的描述 (二)
    MDA(模型驱动架构)
    简单工厂模式
    Windows Communication Foundation(WCF) 一步一步从入门到精通
    UML 状态图
    C# 设计模式与重构
    DSM领域定义建模和MDA模型驱动架构分析
    UML 部署图
    UML 活动图
    UML 及其作用
  • 原文地址:https://www.cnblogs.com/erdanyang/p/10167683.html
Copyright © 2020-2023  润新知