将Python POST请求转换为Android

时间:2014-10-14 07:41:21

标签: java android python post httpurlconnection

我正在尝试将这个Python POST示例用于我的android项目中的API。我对HttpsURLConnection没有太多经验,但我认为这是我需要用来实现这一目标的。我已经看过这方面的教程,但我不确定如何集成这个Python代码。这是Python:

# 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

这是我到目前为止尝试将其转换为Android的方法,但我不确定这是否有用或者是正确的方法。

// 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());

}

非常感谢任何建议。

1 个答案:

答案 0 :(得分:0)

对于REST Web服务,我建议使用https://github.com/47deg/appsly-android-rest。它有一个易于使用的API,你不必太在意后端部分。 我希望你只想在你的Android应用程序中获取数据。但是,如果您只想翻译您的方法,这可能不适合您:)