【发布时间】:2014-04-12 19:08:50
【问题描述】:
我正在尝试使用 Python Requests HTTP 库将此 Python 代码转换为 Java 代码(适用于 Android)。
import requests
payload = {"attr[val1]":123,
"attr[val2]":456,
"time":0,
"name":"Foo","surname":"Bar"}
r = requests.post("http://jakiro.herokuapp.com/api", data=payload)
r.status_code
r.text
这是我到目前为止所做的:
protected void sendJson() {
Thread t = new Thread() {
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try {
Log.v("SOMETHING_NAME3", "Creating POST");
HttpPost post = new HttpPost("http://jakiro.herokuapp.com/api");
json.put(MessageAttribute.SURNAME, "Bar");
json.put(MessageAttribute.VAL1, 123);
json.put(MessageAttribute.VAL2, 456);
json.put(MessageAttribute.name, "Foo");
json.put(MessageAttribute.TIME, 0);
StringEntity se = new StringEntity( json.toString() );
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
String foo = convertStreamToString(in);
Log.v("SOMETHING_NAME2", foo); // Gives me "Bad request"
}
} catch(Exception e) {
e.printStackTrace();
Log.v("SOMETHING_NAME", "Cannot Establish Connection");
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
我检查了response.getStatusLine().getStatusCode() 的响应,并从服务器返回了 400。 Python 代码工作很好,但在 Android 设备上的 Java 中却不行。不过我不知道为什么。
【问题讨论】:
-
在 Python 代码中,
data是百分比编码的。它不是用 JSON 编码的。 -
有趣,那么我会将该对象转换为百分比编码吗?
-
不知道,我不使用 Java。我会想象这样的事情:stackoverflow.com/questions/8120220/…
-
@Blender 太好了,我搞定了!如果您可以将您的评论转换为答案,我很乐意接受。
标签: java android python http post