2014-10-14 2 views
1

내 안드로이드 프로젝트의 API에 파이썬 POST 예제를 사용하려고합니다. 나는 HttpsURLConnection에 대한 많은 경험이 없지만 이것이 이것을 달성하는데 사용해야한다고 생각한다. 이 튜토리얼을 보았습니다 만이 파이썬 코드를 통합하는 방법을 모르겠습니다.Python POST 요청을 Android로 변환

# highly suggested to use the requests package 
# http://www.python-requests.org/en/latest/ 
import requests 
# read in the image and construct the payload 
image = open("example.jpg").read() 
data = {"api_key": "KH8hdoai0wrjB0LyeA3EMu5n4icwyOQo"} 
files = {"image": open("example.jpg")} 
# fire off the request 
r = requests.post("http://www.idmypill.com/api/id/", data = data, files = files) 
# contents will be returned as a JSON string 
print r.content 

이것은 내가 지금까지 안드로이드에이 변환하려고에 있지만 나는이 작동 또는 이것에 대해 갈 수있는 올바른 방법이 전혀 확실하지 않다 무엇 : 이것은 파이썬입니다.

// HTTP POST request 
private void sendPost() throws Exception { 

    String url = "http://www.idmypill.com/api/id/"; 
    URL obj = new URL(url); 
    HttpsURLConnection IDMyPill = (HttpsURLConnection) obj.openConnection(); 

    //add reuqest header 
    IDMyPill.setRequestMethod("POST"); 


    String urlParameters = ""; 

    // Send post request 
    IDMyPill.setDoOutput(true); 
    DataOutputStream wr = new DataOutputStream(IDMyPill.getOutputStream()); 
    wr.writeBytes(urlParameters); 
    wr.flush(); 
    wr.close(); 

    int responseCode = IDMyPill.getResponseCode(); 
    System.out.println("\nSending 'POST' request to URL : " + url); 
    System.out.println("Post parameters : " + urlParameters); 
    System.out.println("Response Code : " + responseCode); 

    BufferedReader in = new BufferedReader(
      new InputStreamReader(IDMyPill.getInputStream())); 
    String inputLine; 
    StringBuffer response = new StringBuffer(); 

    while ((inputLine = in.readLine()) != null) { 
     response.append(inputLine); 
    } 
    in.close(); 

    //print result 
    System.out.println(response.toString()); 

} 

모든 조언을 주시면 감사하겠습니다.

+0

저는 파이썬에 익숙하지 않지만 PHP json_encode(); 파이썬에 있다면. 그런 다음 Android vley를 사용하면 훨씬 간단합니다. – Mike

+0

코드를 실행하면 어떤 일이 일어나는지 시험해보십시오. – Okas

답변

0

REST 웹 서비스의 경우 https://github.com/47deg/appsly-android-rest을 사용하는 것이 좋습니다. 그것은 API를 사용하기 쉽고 당신은 백엔드 부분에 대해 많이 신경 쓸 필요가 없습니다. 안드로이드 앱에서만 데이터를 받고 싶기를 바랍니다. 그러나 당신이 단지 당신의 방법을 번역하고 싶다면 이것은 당신에게 맞지 않을 수도 있습니다 :)

관련 문제