Getting Response code as 400 from geo location api - java

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..

You have to tell the receiving side that it is json that you send
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

Related

Is there an Alternative for AsyncTask using HttpUrlConnection

Using AsyncTask freezes my whole app. i have an icon that rotates while the Http action is happening in the background. but the app just freezes till it finishes that action. Is there an alternative?
The below class sends the JSON to the server, the server has multiple endpoints and stuff like that. now when calling class calls the execute() method, the app freezes until the task is complete.
public class Connector extends AsyncTask<String, Void, Void> {
private String ip = "http://192.168.1.127";
private String port = "5000";
private URL Url;
private JSONObject jsonObject;
private String method = "";
private StringBuilder output = new StringBuilder();
Connector(String url, JSONObject jsonObject, String method)
{
try {
this.method = method;
this.Url = new URL(ip+":"+port+url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
this.jsonObject = jsonObject;
//Connect to URL
}
#Override
protected Void doInBackground(String... strings) {
try {
HttpURLConnection httpURLConnection = (HttpURLConnection) Url.openConnection();
Log.i("Data", "Data sent => " + jsonObject.toString());
try {
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod(method);
httpURLConnection.setRequestProperty("content-type", "application/json");
httpURLConnection.connect();
DataOutputStream outputStream = new DataOutputStream(httpURLConnection.getOutputStream());
if(jsonObject != null)
{
outputStream.writeBytes(jsonObject.toString());
outputStream.flush();
outputStream.close();
}
InputStreamReader inputStreamReader = new InputStreamReader((InputStream) httpURLConnection.getContent(), Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while(line != null)
{
output.append(line);
line = reader.readLine();
}
}finally {
httpURLConnection.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
String getMessge() {
Log.i("Data", "Data received <= " + output.toString());
return output.toString();
}
}
Please use Retrofit library.
You can find samples to use Retrofit easily.
https://www.journaldev.com/13639/retrofit-android-example-tutorial
This is one of them.
Hope it to help you. Thanks.

Android: java.net.ProtocolException: Unexpected status line: HTTP/1.2 200 OK

I have been working on the following code for a while.
the code worked for the 5.x version of my app but I can't get the code to work for Android version 6.x and higher.
public class PostAsync extends AsyncTask<String, Integer, Double> {
private Context _context = null;
public PostAsync(Context context) {
_context = context;
}
#Override
protected Double doInBackground(String... params) {
String serverResponse = postData(params[0]);
try {
JSONObject obj = new JSONObject(serverResponse);
String id = "";
JSONObject locationobj = obj.getJSONObject("X");
JSONObject response = locationobj.getJSONObject("Y");
id = response.getString("id");
Settings.idcode = id;
// Convert , to %2c, since we're working with a URI here
String number = Settings.number + Settings.code + "," + Settings.idcode; // %2c
_context.startActivity(new Intent(Intent.ACTION_CALL).setData(Uri.parse("tel://" + number)));
}
catch (Exception e) {
// TODO: Errorhandler
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Double result) {
}
protected void onProgressUpdate(Integer... progress) {
}
// Send a POST request to specified url in Settings class, with defined JSONObject message
public String postData(String msg) {
String result = null;
StringBuffer sb = new StringBuffer();
InputStream is = null;
try {
URL url = new URL(Settings.webURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setChunkedStreamingMode(0);
connection.setReadTimeout(15000);
connection.setConnectTimeout(15000);
connection.setRequestProperty("Content-Encoding", "identity");
connection.setRequestProperty("Accept-Encoding", "identity");
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setRequestProperty("TYPE", "JSON");
connection.setRequestProperty("KEY", "key");
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(msg);
wr.flush();
wr.close();
int responseCode = connection.getResponseCode();
String responseMessage = connection.getResponseMessage();
System.out.println("Response code: " + responseCode);
System.out.println("Response message: " + responseMessage);
if(responseCode == HttpURLConnection.HTTP_OK){
is = new BufferedInputStream(connection.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String inputLine = "";
try {
while ((inputLine = br.readLine()) != null) {
sb.append(inputLine);
}
result = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
I get the following error
java.net.ProtocolException: Unexpected status line: HTTP/1.2 200 OK
Can someone tell me what I am missing?

What is the proper way of Exception Handling in the following scenario:

I have an Async task which checks for user session. This task is responsible for contacting the server using a method - both are listed below:
public class SessionChecker extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Intent intent;
if (result.equalsIgnoreCase("exception")) {
//We got an exception in URL Connection - letus restart the task -- this is recursive
new SessionChecker().execute();
} else if (result.equalsIgnoreCase("server error")) {
//We got an exception in URL Connection - letus restart the task -- this is recursive
new SessionChecker().execute();
} else {
try {
JSONObject jObj = new JSONObject(result);
if (!TextUtils.isEmpty(result)) {
String message = jObj.getString("message");
if (message.equalsIgnoreCase("failure")) {
intent = new Intent(AppInitializer.this, AppWebViewLogin.class);
startActivity(intent);
} else if (message.equalsIgnoreCase("success")) {
intent = new Intent(AppInitializer.this, NavigationMasterActivity.class);
startActivity(intent);
}
}
} catch (JSONException ex) {
//Malformed JSON - letus restart the task -- this is recursive
new SessionChecker().execute();
}
}
}
#Override
protected String doInBackground(Void... params) {
DomainManager domainManager = new DomainManager(AppInitializer.this);
return UniversalNetworkConnection.simplePost(domainManager.getDomain() + getResources().getString(R.string.url_check_session));
}
}
Here is my URL Connection method:
public static String simplePost(String myurl) {
HttpsURLConnection conn = null;
try {
SSLContext sslcontext = SSLContext.getInstance("TLSv1");
sslcontext.init(null, null, null);
SSLSocketFactory NoSSLv3Factory = new NoSSLv3SocketFactory(sslcontext.getSocketFactory());
HttpsURLConnection.setDefaultSSLSocketFactory(NoSSLv3Factory);
StringBuffer response;
URL url = new URL(myurl);
conn = (HttpsURLConnection) url.openConnection();
// conn.setReadTimeout(90000);
// conn.setConnectTimeout(900000);
conn.setRequestProperty("Content-Type", "application/json");
CookieManager cookieManager = CookieManager.getInstance();
String cookie = cookieManager.getCookie(new URL(myurl).getHost());
conn.setDoOutput(true);
conn.setRequestProperty("Cookie", cookie);
conn.setRequestMethod("POST");
int responseCode = conn.getResponseCode();
switch (responseCode) {
case 200:
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
default:
return "server error";
}
} catch (IOException | java.security.KeyManagementException | java.security.NoSuchAlgorithmException ex) {
ex.printStackTrace();
return "exception";
} finally {
if (conn != null) {
try {
conn.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
return "exception";
}
}
}
}
I have tried handling the exceptions recursively - an exception occurs - The async task is reloaded, how can I improve this, I am not sure if the way I am doing this is the best practice? Any hints / solutions / tips would be really helpful.

Post JSON in android

I want to post String data over HttpClient in android
but i'm tired after receive response status code 503 - service unavailable and
return response as Html code for our url.
I write in the following Code in JAVA Application and i return the data but when I write the same code in Android Application i receive an exception file I/O not found, I'm Puzzled for this case:
public void goButton(View v)
{
try{
URL url = new URL("https://xxxxxxxxx");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Test ts= new ApiRequest("null","getUserbyID",new String[] { "66868706" });
String payLoad = ts.toString(); //toSting is override method that create //JSON Object
System.out.println("--->>> " + payLoad);
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
System.out.println("=================>>> "+ payLoad);
wr.write(payLoad);
wr.flush();
BufferedReader rd = new BufferedReader(new nputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println("-->> " + line);
response += line;
}
wr.close();
rd.close();
System.out.println("=================>>> "+ response);
} catch (Exception e) {
e.printStackTrace();
System.out.println("=================>>> " + e.toString());
throw new RuntimeException(e);
}
I try to put this code in AsynTask, Thread but i receive the same response status code.
I write in the following Android code as an example data
public void goButton(View v)
{
try{
new Thread(new Runnable() {
public void run() {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(),
10000); // Timeout Limit
HttpResponse response;
String url = "https://xxxxxxxxxxxxx";
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost(url);
post.setHeader("Content-type", "application/json");
json.put("service","null");
json.put("method", getUserByID.toString());
json.put("parameters", "1111");
System.out.println(">>>>>>>>>>>" + json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(se);
String response = client.execute(post);
if (response != null) {
String temp = EntityUtils.toString(response.getEntity());
System.out.println(">>>>>>>>>>>" + temp);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(">>>>>>>>>>>" + e.getMessage());
}
}
}).start();
}
Please Help me to find solution for this problem :(
Thank you in advance
Here is an code snippet , hoping it will help you.
1)An function which carries the http get service
private String SendDataFromAndroidDevice() {
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet getMethod = new HttpGet("your url + data appended");
BufferedReader in = null;
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient
.execute(getMethod);
in = new BufferedReader(new InputStreamReader(httpResponse
.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
2) An Class which extends AsyncTask
private class HTTPdemo extends
AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... params) {
String result = SendDataFromAndroidDevice();
return result;
}
#Override
protected void onProgressUpdate(Void... values) {}
#Override
protected void onPostExecute(String result) {
if (result != null && !result.equals("")) {
try {
JSONObject resObject = new JSONObject(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
3) Inside your onCreate method
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView("your layout");
if ("check here where network/internet is avaliable") {
new HTTPdemo().execute("");
}
}
This code snippet ,
Android device will send the data via URL towards Server
now server needs to fetch that data from the URL
Hey Mohammed Saleem
The code snippet provided by me works in the following way,
1)Android device send the URL+data to server
2)Server [say ASP.NET platform used] receive the data and gives an acknowledgement
Now the Code which should be written at client side (Android) is provided to you, the later part of receiving that data at server is
Server needs to receive the data
An webservice should be used to do that
Implement an webservice at server side
The webservice will be invoked whenever android will push the URL+data
Once you have the data ,manipulated it as you want

Http Get using Android HttpURLConnection

I'm new to Java and Android development and try to create a simple app which should contact a web server and add some data to a database using a http get.
When I do the call using the web browser in my computer it works just fine. However, when I do the call running the app in the Android emulator no data is added.
I have added Internet permission to the app's manifest. Logcat does not report any problems.
Can anyone help me to figure out what's wrong?
Here is the source code:
package com.example.httptest;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class HttpTestActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
setContentView(tv);
try {
URL url = new URL("http://www.mysite.se/index.asp?data=99");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.disconnect();
tv.setText("Hello!");
}
catch (MalformedURLException ex) {
Log.e("httptest",Log.getStackTraceString(ex));
}
catch (IOException ex) {
Log.e("httptest",Log.getStackTraceString(ex));
}
}
}
Try getting the input stream from this you can then get the text data as so:-
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://www.mysite.se/index.asp?data=99");
urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
You can probably use other inputstream readers such as buffered reader also.
The problem is that when you open the connection - it does not 'pull' any data.
Here is a complete AsyncTask class
public class GetMethodDemo extends AsyncTask<String , Void ,String> {
String server_response;
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
server_response = readStream(urlConnection.getInputStream());
Log.v("CatalogClient", server_response);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("Response", "" + server_response);
}
}
// Converting InputStream to String
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
To Call this AsyncTask class
new GetMethodDemo().execute("your web-service url");
I have created with callBack(delegate) response to Activity class.
public class WebService extends AsyncTask<String, Void, String> {
private Context mContext;
private OnTaskDoneListener onTaskDoneListener;
private String urlStr = "";
public WebService(Context context, String url, OnTaskDoneListener onTaskDoneListener) {
this.mContext = context;
this.urlStr = url;
this.onTaskDoneListener = onTaskDoneListener;
}
#Override
protected String doInBackground(String... params) {
try {
URL mUrl = new URL(urlStr);
HttpURLConnection httpConnection = (HttpURLConnection) mUrl.openConnection();
httpConnection.setRequestMethod("GET");
httpConnection.setRequestProperty("Content-length", "0");
httpConnection.setUseCaches(false);
httpConnection.setAllowUserInteraction(false);
httpConnection.setConnectTimeout(100000);
httpConnection.setReadTimeout(100000);
httpConnection.connect();
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (onTaskDoneListener != null && s != null) {
onTaskDoneListener.onTaskDone(s);
} else
onTaskDoneListener.onError();
}
}
where
public interface OnTaskDoneListener {
void onTaskDone(String responseData);
void onError();
}
You can modify according to your needs. It's for get
If you just need a very simple call, you can use URL directly:
import java.net.URL;
new URL("http://wheredatapp.com").openStream();
Simple and Efficient Solution : use Volley
StringRequest stringRequest = new StringRequest(Request.Method.GET, finalUrl ,
new Response.Listener<String>() {
#Override
public void onResponse(String){
try {
JSONObject jsonObject = new JSONObject(response);
HashMap<String, Object> responseHashMap = new HashMap<>(Utility.toMap(jsonObject)) ;
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("api", error.getMessage().toString());
}
});
RequestQueue queue = Volley.newRequestQueue(context) ;
queue.add(stringRequest) ;
A more contemporary way of doing it on a separate thread using Tasks and Kotlin
private val mExecutor: Executor = Executors.newSingleThreadExecutor()
private fun createHttpTask(u:String): Task<String> {
return Tasks.call(mExecutor, Callable<String>{
val url = URL(u)
val conn: HttpURLConnection = url.openConnection() as HttpURLConnection
conn.requestMethod = "GET"
conn.connectTimeout = 3000
conn.readTimeout = 3000
val rc = conn.responseCode
if ( rc != HttpURLConnection.HTTP_OK) {
throw java.lang.Exception("Error: ${rc}")
}
val inp: InputStream = BufferedInputStream(conn.inputStream)
val resp: String = inp.bufferedReader(UTF_8).use{ it.readText() }
return#Callable resp
})
}
and now you can use it like below in many places:
createHttpTask("https://google.com")
.addOnSuccessListener {
Log.d("HTTP", "Response: ${it}") // 'it' is a response string here
}
.addOnFailureListener {
Log.d("HTTP", "Error: ${it.message}") // 'it' is an Exception object here
}
URL url = new URL("https://www.google.com");
//if you are using
URLConnection conn =url.openConnection();
//change it to
HttpURLConnection conn =(HttpURLConnection )url.openConnection();

Categories

Resources