Search code examples
javaandroidhttp-status-code-400google-geolocation

Getting Response code as 400 from geo location api


I am trying to use geo location api to get lattitude and longitude of the location. So for this I created a project on developer console and created an api key. I used this api key with this api https://www.googleapis.com/geolocation/v1/geolocate?key=YOUR_API_KEY

So this when I executed the request in postman it works well. But when I tried to execute same request in an app its giving response as response code 400.

Response code 400 as per developer guide

https://developers.google.com/maps/documentation/geolocation/intro#errors

shows it comes when the api key is wrong. But how the key works in postman and not in the app?

Here is the code for server request:

    public JSONObject sendPostRequest1(String data) {

    try {

        URL url = new URL(api);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("POST");
      //  con.setRequestProperty("content-type", "application/x-www-form-urlencoded");
        con.setDoOutput(true);
        con.setDoInput(true);
        OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());

        try {
            writer.write(data);
        } catch (Exception e) {
            Log.e("Exception111", e.toString());
        }

        writer.close();

        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) {
            StringBuilder sb = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            reader.close();
            Log.d("ServerResponse", new String(sb));
            String output = new String(sb);
            return new JSONObject(output);
        } else {
            Log.e("Exception", "" + responseCode);
        }
    }
    catch (JSONException je)
    {
        je.printStackTrace();
        return Excpetion2JSON.getJSON(je);
    }
    catch(IOException e)
    {

    }
    return null;
}

Async Task :

public class GetLocationAsyncTask extends AsyncTask<String, Void, JSONObject> {

    String api;
    JSONObject jsonParams;
    Context mContext;
    private ProgressDialog loadingDialog;
    private String number,code;
    public GetLocationsCallBack getLocationsCallBack;

    public GetLocationAsyncTask(Context context,GetLocationsCallBack getLocationsCallBack) {

        this.mContext = context;
        this.getLocationsCallBack = getLocationsCallBack;

    }

    public interface GetLocationsCallBack {
        void doPostExecute(ArrayList<Location> list);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected JSONObject doInBackground(String... params) {
        try {

            api = "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyCArRAX4oHdfFWrTWhXrOVBQtbs";

            jsonParams = new JSONObject();
            jsonParams.put("cellId", params[0]);
            jsonParams.put("locationAreaCode",params[1]);

            ServerRequest request = new ServerRequest(api, jsonParams);
            return request.sendPostRequest1(jsonParams.toString());

        } catch (Exception ue) {
            return Excpetion2JSON.getJSON(ue);
        }
    }  //end of doInBackground

    @Override
    protected void onPostExecute(JSONObject response) {
        super.onPostExecute(response);


            if(response.has("location"))
            {

                try {

                    Location location = new Location();

                    location.setLattitude(response.getString("lat"));
                    location.setLongitude(response.getString("lng"));

                    ArrayList<Location> locations = location.getLocationArrayList();

                    locations.add(location);
                }
                catch (JSONException je)
                {
                    Log.d("JsonException",je.toString());
                }

            }

        if (loadingDialog.isShowing())
            loadingDialog.dismiss();

    }
}

Executing async task:

        TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
        GsmCellLocation cellLocation = (GsmCellLocation)telephonyManager.getCellLocation();

        int cellid= cellLocation.getCid();
        int celllac = cellLocation.getLac();


        Log.d("CellLocation", cellLocation.toString());
        Log.d("GSM CELL ID",  String.valueOf(cellid));
        Log.d("GSM Location Code", String.valueOf(celllac));

        GetLocationAsyncTask getLocationAsyncTask = new GetLocationAsyncTask(MainActivity.this,MainActivity.this);
        getLocationAsyncTask.execute(String.valueOf(cellid),String.valueOf(celllac));

Whats going wrong with this? Please help. Thank you..


Solution

  • You have to tell the receiving side that it is json that you send

    con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");