简体   繁体   English

从Apache HttpResponse获取响应Uri参数

[英]Get response Uri parameters from apache HttpResponse

I'm sending an http get/head request using Apache HttpClient 4.x. 我正在使用Apache HttpClient 4.x发送http get / head请求。 I'm sending a request with a url like " http://example.com/getAccessToken ". 我正在发送带有“ http://example.com/getAccessToken ”之类的网址的请求。 I'm expecting the response to be a redirect url with parameters in the returned url like " http://redirecturl.com/?code=accessTokenStuff ". 我期望响应是带有返回URL中的参数的重定向URL,例如“ http://redirecturl.com/?code=accessTokenStuff ”。 I want to be able to parse the response redirect url parameters, ie I want to get "accessTokenStuff". 我希望能够解析响应重定向URL参数,即我想获取“ accessTokenStuff”。 How can I do that? 我怎样才能做到这一点?

HttpClient client = new DefaultHttpClient();
            HttpHead request = new HttpHead(authUrl);
            HttpResponse response = client.execute(request);
            System.out.println(response.getStatusLine().getStatusCode());//returns 200

            request.releaseConnection();

In a nutshell: what I want is executing an original url and then getting the result which is another url that has a parameter called "code". 简而言之:我想要执行的是原始网址,然后得到的结果是另一个具有称为“代码”的参数的网址。 Then I want to get the value of that parameter. 然后,我想获取该参数的值。

EDIT: 编辑:

I also tried this but it returns the same original URL 我也尝试过,但是它返回相同的原始URL

DefaultHttpClient client = new DefaultHttpClient();
            HttpParams params = client.getParams();
            HttpClientParams.setRedirecting(params, false);
            HttpGet request = new HttpGet(authUrl);
            HttpResponse response = client.execute(request);
            String location = response.getLastHeader("Location").getValue();//returns same original url
            System.out.println(location);
            request.releaseConnection();

Setting HttpClientParams.setRedirecting(params, true); 设置HttpClientParams.setRedirecting(params, true); return null 返回null

Http response do not take a form of a "redirect url". Http响应不采用“重定向URL”的形式。 Redirect and response are both different (but related) concepts. 重定向和响应都是不同(但相关)的概念。 Redirect usually means "get your response from this address instead of original one". 重定向通常表示“从此地址获得答复,而不是原始答复”。

Having said this, you can prevent HttpClient from following a redirect, see this answer: How to prevent apache http client from following a redirect 话虽如此,您可以阻止HttpClient进行重定向,请参见以下答案: 如何防止apache http客户端进行重定向

When your HttpClient is not following the redirect, you can inspect the 'Location:' header of its response, eg: 当您的HttpClient不遵循重定向时,您可以检查其响应的“ Location:”标头,例如:

HeaderIterator iterator = httpResponse.headerIterator("Location");
while(iterator.hasNext()) {
  Header header = iterator.nextHeader();
  String redirectUrl = header.getValue();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM