HttpClient方式模拟http请求设置头

关于HttpClient方式模拟http请求,请求头以及其他参数的设置。

本文就暂时不给栗子了,当作简版参考手册吧。

 

发送请求是设置请求头:header

HttpClient httpClient = new DefaultHttpClient();  
  
        //創建一個httpGet方法   
  
        HttpGet httpGet = new HttpGet("http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2113252.html"); 
//設置httpGet的头部參數信息 httpGet.setHeader("Accept", "Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); httpGet.setHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7"); httpGet.setHeader("Accept-Encoding", "gzip, deflate"); httpGet.setHeader("Accept-Language", "zh-cn,zh;q=0.5"); httpGet.setHeader("Connection", "keep-alive"); httpGet.setHeader("Cookie", "__utma=226521935.73826752.1323672782.1325068020.1328770420.6;"); httpGet.setHeader("Host", "www.cnblogs.com"); httpGet.setHeader("refer", "http://www.baidu.com/s?tn=monline_5_dg&bs=httpclient4+MultiThreadedHttpConnectionManager"); httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2");

 

收到response时,获取头部信息:

     Header headers[] = response.getAllHeaders();  
  
        int i = 0;  
  
        while (i < headers.length) {  
      System.out.println(headers[i].getName() + ":  " + headers[i].getValue());  
                i++;  
        }  

 

// TODO: 2016/5/26   Httpclient方式设置请求头demo

转自:HttpClient中头部Header的使用

转载于:https://www.cnblogs.com/not-NULL/p/5531763.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您也可以使用Apache HttpClient库来模拟发送POST请求,并将JSON数据作为请求体发送。以下是一个示例代码: ```java import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import java.io.BufferedReader; import java.io.InputStreamReader; public class PostJsonRequest { public static void main(String[] args) { try { // 设置请求URL和JSON数据 String url = "http://example.com/api"; String json = "{\"name\": \"John\", \"age\": 30}"; // 创建HttpClientHttpPost对象 HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(url); // 将JSON数据作为请求体发送 StringEntity entity = new StringEntity(json); post.setEntity(entity); post.setHeader("Content-type", "application/json"); post.setHeader("Accept", "application/json"); // 发送请求并获取响应 HttpResponse response = client.execute(post); // 打印响应内容 BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { System.out.println(line); } } catch (Exception e) { e.printStackTrace(); } } } ``` 在上述示例中,我们使用了Apache HttpClient库来创建HttpClientHttpPost对象,并将JSON数据作为请求体发送。注意:在实际使用时,您需要将URL和JSON数据替换为实际的值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值