Java 将Python POST请求转换为Android
我正试图在我的android项目中使用这个Python POST到API的示例。我对HttpsURLConnection没有太多经验,但我认为这就是我需要使用的来实现这一点。我已经看过这方面的教程,但我不确定如何集成这段Python代码。这就是Python:Java 将Python POST请求转换为Android,java,android,python,post,httpurlconnection,Java,Android,Python,Post,Httpurlconnection,我正试图在我的android项目中使用这个Python POST到API的示例。我对HttpsURLConnection没有太多经验,但我认为这就是我需要使用的来实现这一点。我已经看过这方面的教程,但我不确定如何集成这段Python代码。这就是Python: # highly suggested to use the requests package # http://www.python-requests.org/en/latest/ import requests # read in the
# 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());
}
任何建议都将不胜感激 对于REST Web服务,我建议使用。它有一个易于使用的api,您不必太在意后端部分。
我希望您只想在android应用程序中获取数据。但是,如果您只想翻译您的方法,那么这可能不适合您:我不熟悉python,但我建议您将api输出为json,与php json_encode的行为相同;如果python中有。然后使用android volley进行调用,因为它简单得多。继续并尝试一下如果运行代码会发生什么。