2013-07-20 85 views
0

我需要爲其HttpMime多部分庫使用Apache HttpComponents。然而,使顯然正好與HttpComponents和股票java.net類相同的呼叫時,HttpComponents失敗:Apache HttpComponents失敗,HttpURLConnection對相同的調用起作用

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。 設置看起來與我完全相同,但必須有所不同。它是什麼?

回答

0

這是一個愚蠢的編碼錯誤。

HttpResponse response = new DefaultHttpClient().execute(new HttpGet(targeturl)); 

應該

HttpResponse response = new DefaultHttpClient().execute(htg); 
相關問題