2012-10-24 6 views
4

Google 드라이브에 파일을 업로드 할 수있는 애플리케이션을 작성하려고합니다. 안드로이드에서 API의 유용한 예제를 찾지 못했고, 제공된 라이브러리보다 가볍게 보였으므로 원시 HTTP 요청을 통해이 서비스와 상호 작용하기로했습니다.Android - Google 드라이브 HTTP 요청

나는 다양한 호출과 응답을 얻기 위해 https://developers.google.com/oauthplayground/을 사용했으며 파일 목록을 반환하는 간단한 요청을 작성하려고합니다. 도구를 통해 전송 요청입니다 : 내가 사용 일식이를 복제하는 것을 시도했다

POST /drive/v2/files HTTP/1.1 
Host: www.googleapis.com 
Content-length: 0 
Content-type: application/json 
Authorization: OAuth *token goes here* 

:

URL url = new URL("https://www.googleapis.com/drive/v2/files?v=3"); 
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
conn.setRequestMethod("POST"); 
conn.setRequestProperty("Host:", "www.googleapis.com"); 
conn.setRequestProperty("Content-length:", "0"); 
conn.setRequestProperty("Content-type:", "application/json"); 
conn.setRequestProperty("Authorization:", "OAuth " + token); 

내가 내 응용 프로그램에서 유효한 토큰을 가지고 있고 또한 헤더를 추가하기 위해 노력했다 conn.setRequestProperty("GData-Version:", "3.0") Google 설명서에 지정된대로 나는 응답 코드 400을 얻고있다. 분명히 잘못된 코드가있다.하지만 필자는 앞에서 본 것과 같이 헤더 요청을 작성하지 않았다.

도움을 주시면 감사하겠습니다.

편집 : 내가 더 가지고 좋아 - 지금 401를 얻고있다 - 나는 편집 로그인 할 필요가 없다는 메시지와 함께 : 서버에서 내가 지금 얻고있다 "수신 된 인증 요청을 null의"응답. 내가

"https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + token 

어떤 아이디어에 액세스하여 사용자 정보를 얻을 수

String token = fetchToken(); 
    if (token == null) { 
     return; 
    } 
    URL url = new URL("https://www.googleapis.com/drive/v2/files"); 
    HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
    try { 
     conn.setRequestMethod("POST"); //use post method 
     conn.setDoOutput(true); //we will send stuff 
     conn.setDoInput(true); //we want feedback 
     conn.setUseCaches(false); //no caches 
     conn.setAllowUserInteraction(false); 
     conn.setRequestProperty("HTTP-Version:", "HTTP/1.1"); 
     conn.setRequestProperty("Content-type: ", "application/json"); 
     conn.setRequestProperty("Authorization:","OAuth" + token); 
     } 
     catch (ProtocolException e) 
     { 
      e.printStackTrace(); 
     } 

    OutputStream out = conn.getOutputStream(); 
    try { 
     OutputStreamWriter wr = new OutputStreamWriter(out); 
     wr.write("{\"Method\":\"POST\",\"absoluteURI\"" + 
       ":\"https://www.googleapis.com/drive/v2/files\"," + 
       "\"headers\":{\"Content-Type\":\"application/json\"," + 
       "\"Content-Length\":\"0\"},\"message-body\":\"\"," + 
       "\"access_token\":\"" + 
       token + 
       "\"" + 
       "," + 
       "\"access_token_type\":\"oauth\"}" 
    ); //ezm is my JSON object containing the api commands 
     wr.flush(); 
     wr.close(); 
    } 
    catch (IOException e) { 
    } 
    finally { //in this case, we are ensured to close the output stream 
     if (out != null) 
     out.close(); 
    } 

    int sc = conn.getResponseCode(); 
    if (sc == 200) { 
     Log.i(TAG, "200 OK.."); 
     InputStream is = conn.getInputStream(); 
     String name = getFileName(readResponse(is)); 
     System.out.println(readResponse(is)); 
     //mActivity.show("Hello " + name + "!"); 
     is.close(); 
     return; 
    } else if (sc == 401) { 
     GoogleAuthUtil.invalidateToken(mActivity, token); 
     onError("Server auth error, please try again.", null); 
     Log.i(TAG, "Server auth error: " + readResponse(conn.getErrorStream())); 
     return; 
    } else { 
     System.out.println(sc); 
     onError("Server returned the following error code: " + sc, null); 
     return; 
    } 

내 토큰이 유효해야합니까?

편집 : 나는 그것이 무슨 문제가 있지만 공식 API를 사용 결국되었다 완전히 확실하지, 작업도 없었어이 도움을 찾고 찾는 사람들을위한 - 좋은 작업 예 Google drive SDK 2.0 throws error 400 Bad Request

여기에서 찾을 수 있습니다

답변

1

토큰이 드라이브 범위에 유효합니까? 질문 끝에 말한 테스트는 같은 범위에 있지 않습니다.

또한 Oauht2 토큰이 한 시간 동안 만 유효하다는 사실을 잊지 마십시오. 다른 토큰을 요청하거나 새로 고침 토큰이있는 경우 토큰을 사용해야 할 수 있습니다.

+0

문제가 무엇인지 잘 모르겠지만이 게시물의 예제를 사용하여 공식 API를 구현하여 해결했습니다. http://stackoverflow.com/questions/12888795/google-drive-sdk -2-0- throws-error-400-bad-request – crazyfool

0

POST 대신 HTTPS, GET을 사용하고 베어러 토큰이 작동하면 작동합니다.

사용하여 컬 :

curl -H "Authorization: Bearer {TOKEN}" \ 
-H "Content-Type: application/json" \ 
https://www.googleapis.com/drive/v2/files 

나는 구글이 REST API를 문서화되지 않는 이유를 모르겠어요. 문서를 어딘가에서 찾으면 의견을 말하십시오.