Java Apache HttpComponents失败,HttpURLConnection可用于同一调用
我需要为其Java Apache HttpComponents失败,HttpURLConnection可用于同一调用,java,http,authorization,apache-httpcomponents,Java,Http,Authorization,Apache Httpcomponents,我需要为其httpime多部分libs使用ApacheHttpComponents。但是,当对HttpComponents和stockjava.net类进行显然完全相同的调用时,HttpComponents失败: private void getUrl(URI targeturl, String token) throws IOException { String AUTH = "Authorization"; String OAUTH = "OAuth "; Sys
httpime
多部分libs使用ApacheHttpComponents
。但是,当对HttpComponents
和stockjava.net
类进行显然完全相同的调用时,HttpComponents
失败:
private void getUrl(URI targeturl, String token) throws IOException {
String AUTH = "Authorization";
String OAUTH = "OAuth ";
System.out.println("Impl1:");
HttpGet htg = new HttpGet(targeturl);
htg.addHeader(AUTH, OAUTH + token);
HttpResponse response = new DefaultHttpClient().execute(new HttpGet(targeturl));
System.out.println(response);
String resp = EntityUtils.toString(response.getEntity());
System.out.println(resp);
System.out.println("\nImpl 2:");
HttpURLConnection conn = (HttpURLConnection) uriToUrl(targeturl).openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setRequestProperty(AUTH, OAUTH + token);
System.out.print(conn.getResponseCode());
System.out.println(" " + conn.getResponseMessage());
StringWriter writer = new StringWriter();
IOUtils.copy(conn.getInputStream(), writer);
System.out.println(writer.toString());
}
//for known good uris ONLY
private URL uriToUrl(URI uri) {
try {
return uri.toURL();
} catch (MalformedURLException mue) {
throw new Error(mue); //something is seriously fuxxored
}
}
结果是:
Impl1:
HTTP/1.1 401 Unauthorized [Access-Control-Allow-Headers: Authorization, Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS, Access-Control-Allow-Origin: *, Content-Length: 51, Content-Type: application/json, Date: Sat, 20 Jul 2013 00:03:42 GMT]
{"status":401,"data":null,"error":["Unauthorized"]}
Impl 2:
200 OK
{"status":200,"data":{...},"error":null}
HttpComponents是客户端4.2.5,核心4.2.4,java是1.6.0-24。
设置对我来说是一样的,但肯定有一些不同。这是什么?这是一个愚蠢的编码错误
HttpResponse response = new DefaultHttpClient().execute(new HttpGet(targeturl));
应该是
HttpResponse response = new DefaultHttpClient().execute(htg);