Java:Http请求(一)post

    导包:

   <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpcore</artifactId>
        <version>4.4.6</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.3</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.5.2</version>
    </dependency>

一:无参

1、构造只带URL的 HttpPost 请求:

HttpPost httpPost = new HttpPost(httpUrl);

2、构造请求客户端  httpClient 实例
   (1)默认:    

CloseableHttpClient httpClient = HttpClients.createDefault();

    (2)自定义:

private static final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000).setConnectionRequestTimeout(15000).build();            
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();

3、接受返回的响应请求

CloseableHttpResponse response = httpClient.execute(httpPost);    
HttpEntity entity = response.getEntity();    
String responseContent = EntityUtils.toString(entity, "UTF-8");

二:有参

1、构造HttpPost
    (1)构造只带URL的 HttpPost 请求:

HttpPost httpPost = new HttpPost(httpUrl);

(2)设置 HttpPost 的 header :

 httpPost.setHeader("Content-Type", "*/*");

/*
            1)类型格式:type/subtype(;parameter)? type
            2)主类型,任意的字符串,如text,如果是*号代表所有
            3)subtype 子类型,任意的字符串,如html,如果是*号代表所有
            4)parameter 可选,一些参数,如Accept请求头的q参数, Content-Type的 charset参数。 
            常见的Content-Type媒体格式类型如下:
                text/html : HTML格式    
                text/plain :纯文本格式          
                text/xml :  XML格式    
                image/gif :gif图片格式        
                image/jpeg :jpg图片格式     
                image/png:png图片格式   
                application/xhtml+xml :XHTML格式   
                application/xml     : XML数据格式   
                application/atom+xml  :Atom XML聚合格式       
                application/json    : JSON数据格式   
                application/pdf       :pdf格式     
                application/msword  : Word文档格式   
                application/octet-stream : 二进制流数据(如常见的文件下载)   
                application/x-www-form-urlencoded : <form encType=””>中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)   
            另外一种常见的媒体格式是上传文件之时使用的:
                multipart/form-data : 需要在表单中进行文件上传时,就需要使用该格式
 */

    (3)设置 HttpPost 的 entity :

         方式一:UrlEncodedFormEntity 会将参数以key1=value1&key2=value2的键值对形式发出。
            param参数以List<NameValuePair>来存放"key1=value1&key2=value2"的字符串,或者如果是Map的话直接转化为 List<NameValuePair>。

//直接将键值对一个一个写入List<NameValuePair>                
List<NameValuePair> pairs = new ArrayList<NameValuePair>();                    
NameValuePair pair1 = new BasicNameValuePair("supervisor", supervisorEt.getEditableText().toString());                  
NameValuePair pair2 = new BasicNameValuePair("content", superviseContentEt.getEditableText().toString());                  
NameValuePair pair3 = new BasicNameValuePair("userId", String.valueOf(signedUser.getId()));                                    
pairs.add(pair1);                  
pairs.add(pair2);                  
pairs.add(pair3);                                    
httpPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));                
//将Map转化为List<NameValuePair>                
List<NameValuePair> nameValuePairs = new ArrayList<>();                
for (String key : maps.keySet()) {
    //Map类型参数写进NameValuePair类型的URL参数中去                    
    nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));                
}                
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));


        方式二:StringEntity tringEntity 可以自己指定ContentType,而默认值是 text/plain。所以不指定ContentType的话 不是以键值对形式发出,如果服务器只接收键值对的话就无法正常解析;
            param参数可以为"key1=value1&key2=value2"的一串字符串,或者是jsonObject

StringEntity stringEntity1 = null ;                
//字符串                
String param = "key1=value1&key2=value2";
stringEntity1 = new StringEntity(param);                                
//jsonObject                
StringEntity stringEntity2 = null ;                 
JSONObject postData = new JSONObject();                                    
postData.put("supervisor", supervisorEt.getEditableText().toString());                  postData.put("content", superviseContentEt.getEditableText().toString());                  postData.put("userId", signedUser.getId());                  
stringEntity2 = new StringEntity(postData.toString(), HTTP.UTF_8);            
stringEntity的ContentType设置(详见:常见的Content-Type媒体格式类型)                stringEntity1.setContentType("application/json");            
stringEntity设置完毕                    
httpPost.setEntity(stringEntity1);

2、构造请求客户端    httpClient 实例
    (1)默认:

CloseableHttpClient httpClient = HttpClients.createDefault();

(2)自定义:

private static final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000).setConnectionRequestTimeout(15000).build();
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();

3、接受返回的响应请求
  

CloseableHttpResponse response = httpClient.execute(httpPost);    
HttpEntity entity = response.getEntity();    
String responseContent = EntityUtils.toString(entity, "UTF-8");

 

 

 

 

 

 

 

                                                                                            底线


 

 

 

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值