2013-07-20 1 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);