gpt4 book ai didi

java - 为什么将此 Python POST 请求转换为 Java 不起作用?

转载 作者:太空宇宙 更新时间:2023-11-04 15:03:40 25 4
gpt4 key购买 nike

我正在尝试使用 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 中则不然。但我不明白为什么。

最佳答案

@Blender 的链接是链接中的正确解决方案:How to use parameters with HttpPost

正确的 URL 编码方法是创建 BasicNameValuePairs 并对其进行编码:

postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("param1", "param1_value"));
postParameters.add(new BasicNameValuePair("param2", "param2_value"));

httppost.setEntity(new UrlEncodedFormEntity(postParameters));

关于java - 为什么将此 Python POST 请求转换为 Java 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22287318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com