Home > Mobile >  Sending http request get syntax error 400 message from API on Android
Sending http request get syntax error 400 message from API on Android

Time:11-01

I'm using Positionstack API to build my APP with a location function on Android. The API works well when I test it on java in the local environment. However, it keeps returning a syntax error message and an Error 400 code when I send the request on Android Studio through an activity.

The error message

I/System.out: 400
I/System.out: {"error":{"code":"bad_request","message":"Could not decode value from JSON format. Error was:     \u0022Syntax error\u0022."}}

The class of sending requests. It works well in the local environment but fails on the emulator. It establishes a HttpUrlConnection and uses the GET method to retrieve the result from API. It returns a 400 status code on the Android Studio emulator.

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class NetTest {
    public static String sendRequest(String urlParam, String coordinate){
        HttpURLConnection con = null;
        BufferedReader buffer = null;
        StringBuffer resultBuffer = null;
        InputStream is;

        try{
            // prepare the params and send request
            URL url = new URL(urlParam);
            con = (HttpURLConnection) url.openConnection();
            con.setConnectTimeout(5000);
            con.setReadTimeout(5000);
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type","application/json;charset=UTF-8");
            con.setDoOutput(true);
            con.set
//            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
//            wr.writeBytes("access_key=xxx");
//            wr.writeBytes("query=-33.7,127");
//            wr.flush();
//            wr.close();


            System.out.println("message out");

            // receive response
            int responseCode = con.getResponseCode();
            System.out.println(responseCode);
            if (responseCode == 200) {
                is = con.getInputStream();
            }else {
                is = con.getErrorStream();
            }
            resultBuffer = new StringBuffer();
            String line;
            buffer = new BufferedReader(new InputStreamReader(is,"UTF-8"));
            while ((line = buffer.readLine()) != null){
                resultBuffer.append(line);
            }
            return resultBuffer.toString();


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void main(String[] args) {
        String coordinate = "-33.7,127";
        String url = "http://api.positionstack.com/v1/reverse";
        System.out.println(sendRequest(url,coordinate));
    }
}

  

The manifest


<application 
    android:usesCleartextTraffic="true">
    
    ...

</application>

<uses-permission android:name="android.permission.INTERNET" />

Thanks a lot!

The problem may be the encoding method of Android, but I don't know how to change it, or even see it.

CodePudding user response:

Use this codeblock -> first create jsonObject and add your key values and then set in output Stream. you can use this link for reference -> https://www.baeldung.com/httpurlconnection-post

JSONObject jsonObject = new JSONObject();
            jsonObject.put("access_key", "Enter your access key here");
            jsonObject.put("query", "Enter your query string here");

            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            String jsonString = jsonObject.toString();
            byte[] input = jsonString.getBytes(StandardCharsets.UTF_8);
            wr.write(input, 0, input.length);
            wr.flush();
            wr.close();

Also check the logger for what is sent in request body, use okhttp as search string in logger

CodePudding user response:

Thanks to @abhishekrajak. I think his answer can solve most questions in this case.

In my case, however, I received an Error 403 status code from the API that said that my subscription couldn't use this service. I think the problem is that using OutputStream of HttpUrlConnection will automatically transfer your request method from "GET" to "POST", and my subscription is only able to receive the "GET" service.

Anyway, no doubt that @abhishekrajak 's answer can successfully pass the parameter in the correct encoding.

I solved this problem by using an alternative API. The original API may not be a good choice in the first place.

  • Related