如何在 HttpClient 的请求中添加、设置和获取 Header? [英] How to add,set and get Header in request of HttpClient?

查看:65
本文介绍了如何在 HttpClient 的请求中添加、设置和获取 Header?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我需要在请求中设置标头,并且需要在控制台中打印标头值...所以请举一个例子来做这个 HttpClient 或在我的代码中编辑这个...

In my application I need to set the header in the request and I need to print the header value in the console... So please give an example to do this the HttpClient or edit this in my code...

我的代码是,

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class SimpleHttpPut { 
  public static void main(String[] args) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://http://localhost:8089/CustomerChatSwing/JoinAction");
    try {
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
      nameValuePairs.add(new BasicNameValuePair("userId",
      "123456789"));
      post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

      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 (IOException e) {
      e.printStackTrace();
    }
  }
}  

提前致谢...

推荐答案

可以使用HttpPost,有方法可以给Request添加Header.

You can use HttpPost, there are methods to add Header to the Request.

DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://localhost";
HttpPost httpPost = new HttpPost(url);

httpPost.addHeader("header-name" , "header-value");

HttpResponse response = httpclient.execute(httpPost);

这篇关于如何在 HttpClient 的请求中添加、设置和获取 Header?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆