簡體   English   中英

為什么無法將此Python POST請求轉換為Java?

[英]Why does converting this Python POST request to Java not work?

我正在嘗試使用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的鏈接是該鏈接上的正確解決方案: 如何在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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM