【问题标题】:How to HTTP POST in Android Studio如何在 Android Studio 中进行 HTTP POST
【发布时间】:2019-07-08 05:31:43
【问题描述】:

我正在尝试在 Android 工作室中使用 with 进行 HTTP POST 以检索值。我已经在 POSTMAN 中测试过这个东西,但我不确定如何在 Android Studio 中输入它。请协助我为此创建 HTTP POST 代码。

我正在发 POST 到

ml2.internalpositioning.com/track

用这个身体

{"username":"fyp","location":"location","group":"cowardlycrab","time":1501640084739,"wifi-fingerprint":[{"mac":"04:c5:a4:66:43:7k","rssi":-29}]}

【问题讨论】:

  • @Héctor 如果我回答我应该把我在邮递员中使用的身体放在哪里?
  • 看第二个答案。当我们链接某些内容时,您应该阅读整个内容。
  • 我不太理解第二个答案的代码,这就是我发表评论的原因。对不起@csm_dev
  • 您可以使用网络库,而不是使用 HttpPost,我已在此链接 stackoverflow.com/a/45210317/1501864 中对此进行了解释。这些库将使您的工作比 http 帖子更轻松、更快捷。

标签: android android-networking androidhttpclient


【解决方案1】:
 //call asynctask  like below : 

JSONObject post_dict = new JSONObject();
                    try {
                        post_dict.put("username", "your_username_data");
 post_dict.put("location", "your_location_data");
 post_dict.put("group", "your_group_data");
 post_dict.put("time", "your_time_data");

JSONArray jarr = new JSONArray();
JSONObject jonj = new JSONObject();
jonj.put("mac","your_mac_data");
jonj.put("rssi","your_rssi_data");
jarr.put(jonj);
post_dict.put("wifi-fingerprint", jarr);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    new YourAsyncTask().execute(String.valueOf(post_dict));



//Actual Async Task Class 

      public class YourAsyncTask extends AsyncTask<String, String, String> {
            ProgressDialog progressDialog;

            protected void onPreExecute() {
                progressDialog = ProgressDialog.show(MainActivity.this,
                        "Please Wait...",
                        "Registering Device");
                super.onPreExecute();
            }

            protected String doInBackground(String... params) {
                String JsonResponse = null;
                String JsonDATA = params[0];
                HttpURLConnection urlConnection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL("ml2.internalpositioning.com/track");
                    urlConnection = (HttpURLConnection) url.openConnection();
                    urlConnection.setDoOutput(true);
                    // is output buffer writter
                    urlConnection.setRequestMethod("POST");
                    urlConnection.setRequestProperty("Content-Type", "application/json");
                    urlConnection.setRequestProperty("Accept", "application/json");
                    //set headers and method
                    Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
                    writer.write(JsonDATA);
                    // json data
                    writer.close();
                    InputStream inputStream = urlConnection.getInputStream();
                    //input stream
                    StringBuffer buffer = new StringBuffer();
                    if (inputStream == null) {
                        // Nothing to do.
                        return null;
                    }
                    reader = new BufferedReader(new InputStreamReader(inputStream));

                    String inputLine;
                    while ((inputLine = reader.readLine()) != null)
                        buffer.append(inputLine + "\n");
                    if (buffer.length() == 0) {
                        // Stream was empty. No point in parsing.
                        return null;
                    }
                    JsonResponse = buffer.toString();
                    //response data
                    try {
                    //send to post execute
                        return JsonResponse;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return null;

                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (urlConnection != null) {
                        urlConnection.disconnect();
                    }
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (final IOException e) {
                        }
                    }
                }
                return null;
            }

            @Override
            protected void onPostExecute(String result) {
                if (progressDialog != null)
                    progressDialog.dismiss();
                super.onPostExecute(result);
               //Do something with result
            }
        }

【讨论】:

    【解决方案2】:

    我也尝试发送一个 http 帖子。 我从上面获取代码 并根据我的情况进行更改。 但不幸的是,出了点问题。

    我想将日期发送到我的 Yamaha AV 接收器 RX-A1080。 有一个 Web 界面,我用它记录了 HTTP POST 命令 在火狐浏览器中。 Firefox 浏览器还以紧凑的 CURL 命令语法提供数据,因此 您可以在以下几行中更好地看到 HTTP POST 命令的数据:

    (as a CURL Command)
    curl 
    'http://192.168.0.24/YamahaRemoteControl/ctrl' 
    -H 'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:62.0) Gecko/20100101 Firefox/62.0' 
    -H 'Accept: */*' 
    -H 'Accept-Language: de,en-US;q=0.7,en;q=0.3' 
    --compressed 
    -H 'Referer: http://192.168.0.24/Setup/' 
    -H 'Content-Type: text/xml' 
    -H 'Connection: keep-alive' 
    --data '<?xml version="1.0" encoding="utf-8"?><YAMAHA_AV cmd="PUT"><System><Speaker_Preout><Pattern_1><PEQ><Manual_Data><Front_L><Band_7><Q>0.500</Q></Band_7></Front_L></Manual_Data></PEQ></Pattern_1></Speaker_Preout></System></YAMAHA_AV>'
    

    我将其转换为:https://curl.trillworks.com/#json 得到这个:

    {
    "url":"http://192.168.0.24/YamahaRemoteControl/ctrl",
    "raw_url":"http://192.168.0.24/YamahaRemoteControl/ctrl",
    "method":"post",
    "headers":
    {
       "User-Agent":"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:62.0) 
        Gecko/20100101 Firefox/62.0",
       "Accept":"*/*",
       "Accept-Language":"de,en-US;q=0.7,en;q=0.3",
       "Referer":"http://192.168.0.24/Setup/",
       "Content-Type":"text/xml",
       "Connection":"keep-alive"
    },
    "data":
    {
       "<?xml version":"\"1.0\" encoding=\"utf-8\"?><YAMAHA_AV cmd=\"PUT\"> 
    <System><Speaker_Preout><Pattern_1><PEQ><Manual_Data><Front_L><Band_7><Q>0.500</Q></Band_7></Front_L></Manual_Data></PEQ></Pattern_1></Speaker_Preout></System></YAMAHA_AV>"
    }
    }
    

    我写的代码是: (我不确定 JSONObject 数据中是否有很多斜线???)

        // Gesamt JSON Object
        JSONObject post_dict = new JSONObject();
    
        try {
            post_dict.put("url", "http://192.168.0.24/YamahaRemoteControl/ctrl");
            post_dict.put("raw_url", "http://192.168.0.24/YamahaRemoteControl/ctrl");
            post_dict.put("method", "post");
    
            // headers - JSON Object ////////////////////////////////////////////
    
            JSONObject headers = new JSONObject();
            headers.put("User-Agent","Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:62.0) Gecko/20100101 Firefox/62.0");
            headers.put("Accept","*/*");
            headers.put("Accept-Language","de,en-US;q=0.7,en;q=0.3");
            headers.put("Referer","http://192.168.0.24/Setup/");
            headers.put("Content-Type","text/xml");
            headers.put("Connection","keep-alive");
    
            post_dict.put("headers", headers);
    
            // data - JSON Object ////////////////////////////////////////////
    
            JSONObject data = new JSONObject();
            data.put("<?xml version","\\\"1.0\\\" encoding=\\\"utf-8\\\"?><YAMAHA_AV cmd=\\\"PUT\\\"><System><Speaker_Preout><Pattern_1><PEQ><Manual_Data><Front_L><Band_7><Gain><Val>-200</Val><Exp>1</Exp><Unit>dB</Unit></Gain></Band_7></Front_L></Manual_Data></PEQ></Pattern_1></Speaker_Preout></System></YAMAHA_AV>");
    
            post_dict.put("data", data);
    
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new YourAsyncTask().execute(String.valueOf(post_dict));
    

    谁能告诉我怎么了:-(

    有关 Firefox 执行的记录命令的更多信息 您可以看到以下几行。 (但它们类似于 CURL 命令)

    New Request
    ============
    POST http://192.168.0.24/YamahaRemoteControl/ctrl
    
    Request-Header:
    ===============
    Host: 192.168.0.24
    User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:62.0) Gecko/20100101 Firefox/62.0
    Accept: */*  
            Accept-Language: de,en-US;q=0.7,en;q=0.3
            Accept-Encoding: gzip, deflate
            Referer: http://192.168.0.24/Setup/
            Content-Type: text/xml
            Content-Length: 272
            Connection: keep-alive
    
    Request-Body:
    =============
    <?xml version="1.0" encoding="utf-8"?>
    <YAMAHA_AV cmd="PUT">
        <System>
            <Speaker_Preout>
                <Pattern_1>
                    <PEQ>
                        <Manual_Data>
                            <Front_L>
                                <Band_7>
    
                                    <Gain>
                                        <Val>-10</Val>
                                        <Exp>1</Exp>
                                        <Unit>dB</Unit>
                                    </Gain>
                             or
                                    <Freq>1.26 kHz</Freq>
                             or
                                    <Q>0.500</Q>
    
                                </Band_7>
                            </Front_L>
                        </Manual_Data>
                    </PEQ>
                </Pattern_1>
            </Speaker_Preout>
        </System>
    </YAMAHA_AV>
    

    【讨论】:

      【解决方案3】:

      我的错误是我的数据不是 json 对象。 我只需要将“数据”作为字符串发送。 然后它起作用了;-)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多