为什么将这个Python POST请求转换为Java不成功?

2 投票
1 回答
1884 浏览
提问于 2025-04-17 21:33

我正在尝试把这段使用Python Requests库的代码转换成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代码却不行。我就是搞不清楚为什么。

1 个回答

1

@Blender提供的链接是正确的解决方案,链接地址是:如何在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));

撰写回答