从apache HttpResponse获取响应Uri并解析它(java)

时间:2012-11-27 15:15:08

标签: java .net http httpresponse

我需要从HttpResponse获取响应uri并将其解析为名称 - 值对。 我需要以下.NET片段的模拟:

string authorizationRequestParameters = string.Format("client_id={0}&response_type=code&scope={1}&access_type=offline", ClientID, Scope);
Uri authorizationRequestUri = new Uri(OauthHost.AbsoluteUri + "?" + authorizationRequestParameters);
HttpWebResponse authorizationResponse = DoGet(authorizationRequestUri, cookies);
NameValueCollection authorizeResponseParameters = HttpUtility.ParseQueryString(authorizationResponse.ResponseUri.Query);
string callbackCode = authorizeResponseParameters["code"];

必要条件是,在Java版本中,DoGet方法返回apache HttpResponse。 我尝试这样做的方式:

HttpResponse resp = hch.doGet("http://...?client_id=...&response_type=...&scope=...&access_type=...");
HttpEntity entity = resp.getEntity();
InputStream instream = entity.getContent();
System.out.print(IOUtils.toString(instream, "UTF-8"));

我可以通过这种方式接收html内容,但我只需要响应包含参数的部分Uri。 我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

似乎HttpWebResponse.ResponseUri属性来自Content-Location标头,或者它是请求URI。所以这样的事情应该有效:

final String uri = "http://...?client_id=...&response_type=...&scope=...&access_type=...";
final HttpResponse resp = hch.doGet(uri);
final String contentLocation = resp.getFirstHeader ("Content-Location");
final String responseURI = contentLocation != null ? contentLocation : uri;