0

I'm trying to do a HTTP POST in Android studio using with to retrieve values. I have already tested the thing in POSTMAN but I'm unsure of how to type it in Android studio. Please assist me in creating the HTTP POST Code for this.

i'm doing a POST to

ml2.internalpositioning.com/track

with this body

{"username":"fyp","location":"location","group":"cowardlycrab","time":1501640084739,"wifi-fingerprint":[{"mac":"04:c5:a4:66:43:7k","rssi":-29}]}
Sneh Pandya
  • 8,197
  • 7
  • 35
  • 50
Luke Au
  • 9
  • 7
  • https://stackoverflow.com/questions/4457492/how-do-i-use-the-simple-http-client-in-android – Héctor Aug 08 '17 at 08:28
  • @Héctor if I that answer where do I put the body that I use in the POSTMAN? – Luke Au Aug 08 '17 at 08:41
  • Look at the 2nd answer. When we link something you should read the entire thing. – takendarkk Aug 08 '17 at 16:02
  • I do not understand the code for the 2nd answer that well, thats why I made that comment. Sorry @csm_dev – Luke Au Aug 09 '17 at 04:41
  • Instead of using HttpPost you can go for network libararies, which I have explained in this link https://stackoverflow.com/a/45210317/1501864. These libraries will make your work easier and faster than the http post. – Jeevanandhan Aug 10 '17 at 10:55

3 Answers3

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
            }
        }
Bapusaheb Shinde
  • 839
  • 2
  • 13
  • 16
1

i also try to send a http post. I take the code from above and change it for my case. But unfortunately there is something wrong.

I want to send Date to my Yamaha AV Receiver RX-A1080. There is a Web Interface and with this I record the HTTP POST Command in Firefox Browser. The Firefox Browser delivers also the data in a compact CURL command syntax so you see better the data of the HTTP POST command in the following lines:

(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>'

i convert that with: https://curl.trillworks.com/#json and get this:

{
"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>"
}
}

The Code i was written was that: ( i am not sure if there are to many slashes in JSONObject data ??? )

    // 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));

Could somebody say me whats wrong :-(

For more Information of the recorded command done by Firefox you can see the following lines. (But they are similiar to the CURL Command)

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>
Oli
  • 11
  • 1
0

My mistake was that my data is not a json object. I only have to send the "data" as a string. Then it works ;-)

Oli
  • 11
  • 1