gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:34:16 25 4
gpt4 key购买 nike

在我的应用程序中,我需要在请求中设置 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com