如何在Android Studio中进行HTTP POST

问题描述 投票:0回答:2

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

我正在做一个帖子

ml2.internalpositioning.com/track

用这个身体

{"username":"fyp","location":"location","group":"cowardlycrab","time":1501640084739,"wifi-fingerprint":[{"mac":"04:c5:a4:66:43:7k","rssi":-29}]}
android android-networking androidhttpclient
2个回答
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
            }
        }

1
投票

我也试着发一个http帖子。我从上面获取代码并根据我的情况进行更改。但不幸的是有些不对劲。

我想将日期发送到我的Yamaha AV接收器RX-A1080。有一个Web界面,我在Firefox浏览器中记录了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>

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.