java - 如何在 HttpClient 的请求中添加、设置和获取 Header?

标签 java http servlets httpclient apache-httpclient-4.x

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

我的代码是,

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。

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

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

HttpResponse response = httpclient.execute(httpPost);

关于java - 如何在 HttpClient 的请求中添加、设置和获取 Header?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13743205/

相关文章:

java - Java包装器方法练习的问题

java - SvnOperationFactory获取svn "add"操作的方法

java - 游戏编程ai : scaling walls to find a player?

java - HTTP 客户端必须关闭其连接

java - Tomcat 7 一直给我一个 404。我做错了什么?

java.lang.ClassNotFoundException : javax. servlet.ServletContainerInitializer 异常

java - JAVA中如何从URL中获取不省略空格的字符串

java - 如何使用 java servlet 和 HttpURLConnection 对文件传输进行校验和

http - 如何在 HTTP1.1 中进行标准的符合 GET 查询

java - 从预定义数据构建 HttpServletRequest