首页 \ 问答 \ 获取请求的自定义标头(Java HTTP)(Fetching a custom header of a request (Java HTTP))

获取请求的自定义标头(Java HTTP)(Fetching a custom header of a request (Java HTTP))

我正在尝试通过Java实现网页的get请求(使用Apache HTTP API)。

网页在get请求中发送自定义标头值,我无法在java代码中模拟。

当我打开一个网页时,它会发送一个请求标题“AO-7DEABF”,其中包含一些自动生成的值(登录会话的值是一致的),除非我通过我的java代码发送相同的值,否则网页不会响应。

如何从我的java代码中获取网页的实际值,以便我可以将其与我的请求一起发送。

我正在使用示例代码

import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Request;

public class Test{
    public static void main(String args[]){
        HttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
        CookieStore cookieStore = new BasicCookieStore();
        Executor executor = Executor.newInstance(client).use(cookieStore);

        String url = "www.sampleurl.com";
        Request req = Request.Get(url);
        String response = executor.execute(request).returnContent().asString();
    }
}

请求标题

GET /rest/zephyr/latest/zql/executeSearch/?zqlQuery=&offset=20&maxRecords=0&expand=executionStatus&_=1444386966596 HTTP/1.1
Host: jira.devops.mnscorp.net
Connection: keep-alive
Accept: application/json, text/javascript, */*; q=0.01
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36
AO-7DEABF: Vwl8V0kdk7Xvyq9BFivbLpbSdpZ2tFjy182i1qYBju0o0KyWAPh9chbJvt9GRGvvf98RK8u1GHaclCm8FBEhbA==
Content-Type: application/json
Referer: https://<myclientjira>/secure/enav/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Cookie: wb48617274=C9B5D1A8; seraph.rememberme.cookie=24122%3A41d5dae1cd459348abecfb0ca5feee6766fd0ac0; JSESSIONID=1428066D5584823DFD572189A2456540; atlassian.xsrf.token=BSMP-3NDP-M3AB-8R70|98ba98938704a930babccb4a5912c01b762d9220|lin; wb48617274=90986387

I am trying to implement a get request of a webpage through Java (using Apache HTTP API).

The webpage is sending an custom header value in the get request which i am not able to simulate in the java code.

When i open a webpage it sends a request header "AO-7DEABF" with some auto-generated value (value is consistent for a login session), and the web page would not respond unless i send the same value through my java code.

How do i fetch the actual value from a web-page from my java code, so that i can send it along with my request.

Sample Code im am using

import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Request;

public class Test{
    public static void main(String args[]){
        HttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
        CookieStore cookieStore = new BasicCookieStore();
        Executor executor = Executor.newInstance(client).use(cookieStore);

        String url = "www.sampleurl.com";
        Request req = Request.Get(url);
        String response = executor.execute(request).returnContent().asString();
    }
}

Request Header

GET /rest/zephyr/latest/zql/executeSearch/?zqlQuery=&offset=20&maxRecords=0&expand=executionStatus&_=1444386966596 HTTP/1.1
Host: jira.devops.mnscorp.net
Connection: keep-alive
Accept: application/json, text/javascript, */*; q=0.01
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36
AO-7DEABF: Vwl8V0kdk7Xvyq9BFivbLpbSdpZ2tFjy182i1qYBju0o0KyWAPh9chbJvt9GRGvvf98RK8u1GHaclCm8FBEhbA==
Content-Type: application/json
Referer: https://<myclientjira>/secure/enav/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Cookie: wb48617274=C9B5D1A8; seraph.rememberme.cookie=24122%3A41d5dae1cd459348abecfb0ca5feee6766fd0ac0; JSESSIONID=1428066D5584823DFD572189A2456540; atlassian.xsrf.token=BSMP-3NDP-M3AB-8R70|98ba98938704a930babccb4a5912c01b762d9220|lin; wb48617274=90986387

原文:https://stackoverflow.com/questions/33032800
更新时间:2021-06-08 15:06

最满意答案

您可以在响应中获取标题详细信息,如下所示。

//get all headers       
Header[] headers = response.getAllHeaders();
for (Header header : headers) {
    System.out.println("Key : " + header.getName() + " ,Value : " + header.getValue());
}

//get header by 'key'
String server = response.getFirstHeader("xxxx").getValue();

you can take the header details in the response as below.

//get all headers       
Header[] headers = response.getAllHeaders();
for (Header header : headers) {
    System.out.println("Key : " + header.getName() + " ,Value : " + header.getValue());
}

//get header by 'key'
String server = response.getFirstHeader("xxxx").getValue();

相关问答

更多

如何在HTTP请求中使用urllib2发送自定义标头?(How do I send a custom header with urllib2 in a HTTP Request?)

不完全的。 创建Request对象实际上并不发送请求,Request对象没有Read()方法。 (另外: read()是小写的)所有你需要做的是将Request作为第一个参数传递给urlopen() ,这将给你你的响应。 import urllib2 request = urllib2.Request("http://www.google.com", headers={"Accept" : "text/html"}) contents = urllib2.urlopen(request).read ...

reactjs axios获取自定义标头的请求(reactjs axios get request with custom header)

axios({ url: 'http://127.0.0.1/myapi/test.php', method: 'get', headers: { 'X-Id-Token': 'abc123abc123', 'Content-Type': 'application/json' } }) .then(response => { console.log(response) }) .catch(err => { c ...

php中的自定义http请求标头(custom http request header in php)

php curl包装器文档说你需要将一个数组传递给这个选项。 请参阅: http : //php.net/manual/en/function.curl-setopt.php 所以这可能有效: <?php $ch = curl_init(); curl_setopt_array($ch, array( CURLOPT_RETURNTRANSFER => true, CURLOPT_URL => 'www.exampleapi.come', CURLOPT_USERPWD = ...

在angularjs中的http请求中添加自定义标头(adding a custom header in http request in angularjs)

我假设_helper.server.http是一个不同的函数,我认为你在传递标题时犯了一个错误 您必须将标头作为对象发送 var customHeader = {'X-user': 'pqrs'} 至 var hello = _helper.server.http($http, url, customHeader) 在_helper.server中的函数http下,你必须在那里添加标题,然后调用http post方法, http: function($http, urlParam, param ...

获取请求的自定义标头(Java HTTP)(Fetching a custom header of a request (Java HTTP))

您可以在响应中获取标题详细信息,如下所示。 //get all headers Header[] headers = response.getAllHeaders(); for (Header header : headers) { System.out.println("Key : " + header.getName() + " ,Value : " + header.getValue()); } //get header by 'key' String server ...

带有自定义标头的Windows Phone 8 Http请求(Windows Phone 8 Http request with custom header)

你在哪里设置标题? 这是怎么做的: request.Headers["mycustomheader"] = "abc"; Where do you set the header? Here is how to do it: request.Headers["mycustomheader"] = "abc";

如何在HTTP请求上设置模块特定的自定义标头?(How can I set module specific custom headers on a HTTP request?)

很明显,只有通过使用模块分离才能解决这个问题,因为您发现$ http服务位于“ng”模块中,该模块自动包含在内。 当您注入$ http时,您将获得在'ng'内置模块中定义的相同实例。 您最好的选择可能是编写用于两个工厂/服务对象的基类,每个工厂/服务对象抽象掉实际调用并设置适当的标头。 这里的API抽象层实现的基础很好https://gist.github.com/jelbourn/6276338 Pretty sure this can't be solved just by separatio ...

Backgrid / Backbone可分页:具有GET请求的自定义HTTP标头(Backgrid/Backbone Pageable: Custom HTTP Headers with GET Request)

覆盖MyCollection的同步方法: var MyCollection = Backbone.PageableCollection.extend({ ... sync: function(method, model, options){ options.beforeSend: function(xhr){ xhr.setRequestHeader('X-Cust-Request-Header', myCustomRequestHeader); return Backbone.s ...

相关文章

更多

最新问答

更多
  • 未捕获的不变违规:addComponentAsRefTo(...):只有ReactOwner可以有refs(Uncaught Invariant Violation: addComponentAsRefTo(…): Only a ReactOwner can have refs)
  • 通过嵌入式YouTube / Flash视频避免滚轮劫持(Avoid scroll-wheel hijack by embedded youtube / flash video)
  • 如何在多用户环境中处理表单编辑?(how to handle form editing in a Multi-user environment?)
  • PHP关闭MySQL连接(PHP close MySQL connection)
  • 我要微信下载
  • Solr dataimport处理程序查询(Solr dataimport handler query)
  • GIT是什么车.
  • Powershell错误处理和空结果(Powershell Error Handling and Null results)
  • Laravel按第二级值排序第一级集合(Laravel sorting 1st level collection by 2nd level value)
  • logback.xml到logback属性文件(logback.xml to logback property file)
  • 使用fgets和strcat时出现问题(Problems when using fgets and strcat)
  • 绘制熊猫数据框两栏(plot pandas dataframe two columns from)
  • 超全球$ _GET中是否保证键值对的顺序?(Is the order of key-value pairs guaranteed in the superglobal $_GET?)
  • C# - 检查两组索引值(C# - Checking Index values of two sets)
  • 模板中的URL输出为空(URL output in template is empty)
  • 关于redhat linux 9.0的三个镜像文件
  • 为什么要在go中分配对struct的引用?(Why assign a reference to a struct in go?)
  • Datagrid点击事件(Datagrid click event)
  • window.location.href在输入press时返回undefined(window.location.href on enter press returns undefined)
  • Javascript Array.remove()作者:John Resig - 为什么要在for-in语句中枚举?(Javascript Array.remove() by John Resig - why does it enumerate in for-in statement?)
  • sudo gem安装cocoapods --pre错误(sudo gem install cocoapods --pre error)
  • 加载完成后,在所有已加载的HTML文件中执行某些操作(After Load Complete, Do Something in All Loaded HTML Files)
  • 如何为wpf datagrid行应用样式(How to have style applied for wpf datagrid row)
  • 在debian上升级内核[关闭](Upgrade kernel on debian [closed])
  • 无法使用JavaScript FileReader API上传二进制文件(Trouble uploading binary files using JavaScript FileReader API)
  • 工作简历怎样写啊?电脑方面的
  • 查找通过gmail API检索的环聊和聊天消息的时间戳(Find timestamp for hangout and chat messages retrieved with gmail api)
  • 如果在汇编程序中没有退出系统调用,会发生什么情况?(What happens if there is no exit system call in an assembly program?)
  • 无法从Intranet访问Wordpress门户(Wordpress portal not accessible from intranet)
  • PDFBox:禁用字体缓存或更改其位置(PDFBox: Disable Font Cache or change its location)