Tried POST in AndroidStudio (error 400)

0

I'm doing an App on Android and I need to connect to an API hosted on localhost.

                   /** Creating Connection **/
                URL serverAddress = new URL(link);
                HttpURLConnection connection = (HttpURLConnection) serverAddress.openConnection();
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setRequestProperty("Content-Type", "Mozilla/5.0");
                connection.setRequestMethod("POST");

                // JSON
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("number", number);

                /** POSTing **/
                OutputStream os = connection.getOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                writer.write(jsonObject.toString());
                writer.flush();
                writer.close();
                os.close();
                connection.connect();

                Log.e("AdvancedNotifications", "sending " + jsonObject.toString() + " to " + link);
                Log.e("AdvancedNotifications", "response code: " + String.valueOf(connection.getResponseCode()));
                Log.e("AdvancedNotifications", "response msg: " + connection.getResponseMessage());

And it gives me error 400 (Bad request).

I've tried Python with requests and it works.

When testing the request from Python by having it print the POST in the console, it gives me this:

192.168.0.158 - - [25/Oct/2018 14:10:35] "POST /call HTTP/1.1" 200 -
{'number': '1642555315'}

And doing it with the request from the App gives me this:

192.168.0.158 - - [25/Oct/2018 14:11:40] "POST /call HTTP/1.1" 400 -

EDIT: When making the request with CURL, I get this error:

{"message": {"number": "Missing required parameter in the post body"}}
    
asked by PiterMcFlebor 25.10.2018 в 14:22
source

2 answers

0

This is how I make a POST request:

InputStream inputStream = null;
String result = "";
try {
        HttpClient httpclient = new DefaultHttpClient();
        // 2. make POST request to the given URL
        HttpPost httpPost = new HttpPost(posturl);

        String json = "";

        // 3. build jsonObject
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("number", number);

        // 4. convert JSONObject to JSON to String
        json = jsonObject.toString();

        // 5. set json to StringEntity
        StringEntity se = new StringEntity(json);

        // 6. set httpPost Entity
        httpPost.setEntity(se);

        // 7. Set some headers to inform server about the type of the content
        httpPost.setHeader("Content-type", "application/json; charset=utf-8");

        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httpPost);

        // 9. receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();

        // 10. convert inputstream to string
        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "ERROR";

    } catch (Exception e) {

        //Log.d("InputStream", e.getLocalizedMessage());
        result="EXCEPTION";
    }

    // 11. return result
    return result;

This call would be made from an HttpAsynkTask. In my case, by parameter I pass the url to which we are going to "attack", it is the posturl parameter.

I have included in the json your number parameter, if you have to send more values in the json, you add them as number is added.

    
answered by 25.10.2018 в 15:14
0

HTTP status 400 means Bad Request . That is, the request has something wrong that causes the server to reject it. The possible reasons can be many: fields that are missing or with invalid values, incorrect or missing headers, incorrect POST body format ... etc. Let's see the code:

The first thing I've noticed is that you have

connection.setRequestProperty("Content-Type", "Mozilla/5.0");

That does not make sense because the content you send is JSON, so it should be "application/json" .

On the other hand, your test with cURL returns

{"message": {"number": "Missing required parameter in the post body"}}

Although you do not indicate it, I assume that the HTTP status is also 400 because it is telling you that in the request you have not included the number field and it is required (mandatory).

    
answered by 25.10.2018 в 15:50