there are some some web site that call end point and recive a json response.
I would like to know how in myAndroid app i can call the web site and retrive the json data that he show.
Example: this is a drivenow site map
drivenow map link
if i open debug mode of browser i see this ajax call that give a josn response.
I would like to know i can call this website and take (grap) this response in my android app so i can use the json
Any idea? Help?
Thanks
You can perform GET/POST request using two ways.
Some 3rd party network request libraries
I would suggest using robospice. Using robospice you perform a network request and give it a POJO. For more info on POJO refer to the link below
https://github.com/stephanenicolas/robospice/wiki/Starter-Guide
What is RoboSpice Library in android
Using native Android/Java code
Use this function to get JSON from URL.
public static JSONObject getJSONObjectFromURL(String urlString) throws IOException, JSONException {
HttpURLConnection urlConnection = null;
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setDoOutput(true);
urlConnection.connect();
BufferedReader br=new BufferedReader(new InputStreamReader(url.openStream()));
char[] buffer = new char[1024];
String jsonString = new String();
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
jsonString = sb.toString();
System.out.println("JSON: " + jsonString);
return new JSONObject(jsonString);}
Then use it like this:
try{
JSONObject jsonObject = getJSONObjectFromURL(String urlString);
// Parse your json here
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
Do not forget to add Internet permission in your manifest
<uses-permission android:name="android.permission.INTERNET" />
For more info on parsing JSON visit
How to parse JSON in Android
Note
You don't have to manually parse your json if you use a 3rd party library.
Related
I am working on an Android App, App is using GET Request to connect with server.
The code I have written to connect with server is working perfectly on many devices.
But its not giving good response on LENOVO YOGA TAB3, It returns Html tags instead of JSON text, Firstly I was confused that there may be some issue in the API URL but I checked URL using browser, Its returning good response so I am sure URL is correct.
Here are API URL and its response :
API URL
[http://www.xyz.in/xyzapi/?building=on&address=Assotech Sandal Suites, Sector 135, Noida, Uttar Pradesh 201304, India&bill_amount=12500&type=R&fullstatename=Uttar Pradesh&lat=28.496171099999998&lng=77.4027049&state=UP&country=IN&district=Gautam Buddha Nagar&sublocality=Sector 135&calc-sess=59d4beba305f3&netmetering=1][1]
Response on Many Android Phones:
{"lifetimesaving":"25.0 Lacs","proposed_pv_capacity":10,"billWithSolar":3872,"bill_amount":"12500","sanction":10,"project_cost":"6.0 Lacs","return_oninevstment":"20.8","roi_image":"solar_score6_6.png","treeadded":"346 ","treeofftheroad":"9 "}
Response on Lenovo Yoga Tab3:
<head/><style>.personal-details h2{font-size:34px}.netmetering-tgle{position:absolute;left:0;right:0;bottom:5px;width:211px}.netmetering-tgle .wnm{float:left;position:relative;padding:0 10px 0 0;min-width:130px;text-align:center}.netmetering-tgle .wnm a{color:#c97511;background:none}#radioBtn .btn{border:1px solid transparent;border-radius:0!important;font-family:"Din-Bold"}#radioBtn .notActive{color:#c97511;background-color:#e0e1e2;padding:2px 0;width:38px;background-size:100% 100%;border-color:transparent;font-family:"Din-Bold";border-radius:5px}#radioBtn .active{color:#fff;background-color:#addc6f;border-color:transparent;padding:2px 5px;width:38px;cursor:auto;pointer-events:none;border-radius:5px;box-shadow:inset 0 0 10px rgba(0,0,0,.8)}#radioBtn .notActive[data-
So response is incorrect on Yoga Tab3.
Here is the code I am using to connect with Server :
public static String connectToServerUsingGETMethod(String API_COMPLETE_URL){
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(API_COMPLETE_URL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
String line = "";
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
//get the string version of the response data
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return "";
}
Suggest me If I can add something in this code so that it can work on Yoga Tab 3 too.
I think you should set static content type when making request to make sure the response sent back is JSON. Similarly, it looks like below:
HttpURLConnection urlConnection = null;
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
Hope it works for you.
I want to share database between an android application and a web application build using Asp.net (my database is based on an IIS server.)
I just want to find the possible ways available to do it, and if I could use php services with IIS server.
I would be so thankful if someone could help me.
Million ways. I can advise you this one: create REST or SOAP service which will have access to database with all methods you need. Now in android application and in ASP.NET application you can "ask" your service to create/update/delete/do something.
try with below code.Hope it will resolved your query.
/**
* This method is used for getting user response after sending request to server.
* It returns the response after executing url request.
* #param params
* #return
*/
public String getJSONObject(String params)
{
try
{
URL url = null;
String response = null;
String parameters = "param1=value1¶m2=value2";
//url = new URL("http://www.somedomain.com/sendGetData.php");
url = new URL(params);
//create the connection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setReadTimeout(40000);
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
//set the request method to GET
connection.setRequestMethod("GET");
//get the output stream from the connection you created
OutputStreamWriter request = new OutputStreamWriter(connection.getOutputStream());
//write your data to the ouputstream
request.write(parameters);
request.flush();
request.close();
String line = "";
//create your inputsream
InputStreamReader isr = new InputStreamReader(
connection.getInputStream());
//read in the data from input stream, this can be done a variety of ways
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
//get the string version of the response data
response = sb.toString();
//do what you want with the data now
//always remember to close your input and output streams
isr.close();
reader.close();
}
catch (Exception e)
{
Log.e("HTTP GET:", e.toString());
response="";
}
return response;
}
I am trying to fetch JSON data from open weather map api with following code but it always gets fail. I dont know what exception happens and I always get null response as defined in the catch.
try {
//URL url = new URL(String.format(OPEN_WEATHER_MAP_API, city));
URL url = new URL(String.format(OPEN_WEATHER_MAP_API));
HttpURLConnection connection =
(HttpURLConnection)url.openConnection();
connection.addRequestProperty("x-api-key",
context.getString(R.string.open_weather_maps_app_id));
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuffer json = new StringBuffer(1024);
String tmp="";
while((tmp=reader.readLine())!=null)
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject(json.toString());
// This value will be 404 if the request was not
// successful
if(data.getInt("cod") != 200){
return null;
}
return data;
}catch(Exception e){
return null;
}
Without, knowing how you are creating your URL, it looks like you are missing the city in your String.format
URL url = new URL(String.format(OPEN_WEATHER_MAP_API));
Shouldn't it be
URL url = new URL(String.format(OPEN_WEATHER_MAP_API, city));
I'm commenting here as I don't have privilege to comment in your question thread.
Print stack trace of your catch block, you may be able to find solution to your problem.
I had to add the following permission along with internet permission.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
what URL you have assigned to your OPEN_WEATHER_MAP_API..?
url should be- http://api.openweathermap.org/data/2.5/weather?q=city&units=metric
please try this...
I posted the code I used for reading the data from my server but I don't know how to send a json frame to the server.
I want to send the data string.
try {
URL url = new URL(params[0]);
con = (HttpURLConnection)url.openConnection();
con.connect();
InputStream in = con.getInputStream();
red = new BufferedReader(new InputStreamReader(in));
String line = "";
buffer = new StringBuffer();
while ((line=red.readLine())!= null){
buffer.append(line);
}
return buffer.toString();
I would assume that you are trying to post some JSON Object to a URL,
While using HttpURLConnection for connection you can set to its instance that this is a POST header request, if you are indeed posting something on that URL.
After that you can use DataOutputStream instance to write(POST) your JSON data something like this.
I have written a snippet which you can check, the code is also available on Github
private class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
/**
* Kindly change this url string with your own, where you want to post your json data
*/
URL url = new URL("");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
// when you are posting do make sure you assign appropriate header
// In this case POST.
httpURLConnection.setRequestMethod("POST");
httpURLConnection.connect();
// like this you can create your JOSN object which you want to send
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("email", "dddd#gmail.com"); //dummy data
jsonObject.addProperty("password", "password");// dummy data
// And this is how you will write to the URL
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(jsonObject.toString());
wr.flush();
wr.close();
Log.d("TAG", "" + IOUtils.toString(httpURLConnection.getInputStream()));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
This code uses apache-common-io, to get the String from the input stream, if you would like you can change that.
Today I'm making my first attempt of sending a POST request with a JSON to save some data, and I'm not being able to do so.
My app works by signing in, and then save, modify and delete data. It's already done in iOS, but since I'm new to Android, I'm not sure how to do it.
Here's my POST function:
public String POST(String targetURL, String urlParameters, String user, String pwd) {
URL url;
String u = targetURL;
HttpURLConnection connection = null;
try {
// Create connection
// u=URLEncoder.encode(u, "UTF-8");
url = new URL(u);
connection = (HttpURLConnection) url.openConnection();
// cambiarlo luego al usuario q esta logeado
String login = user + ":" + pwd;
String encoding = new String(org.apache.commons.codec.binary.Base64.encodeBase64(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(login)));
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization", "Basic " + encoding);
connection.setRequestProperty("Content-Type", "plain/text");// hace q sirva con el string de json
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setReadTimeout(120000);
// Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
// Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
this.setResponseCode(connection.getResponseCode());
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
The method above is executed with Asynctask, and even if I use it to Login using Spring security, it works, and even I can save for internal usage the username, password, and secret token.
I dunno if I need to put the token in a header or something, because I already did that, with no positive results.
I'm supposing that the only permission I need to execute this is the internet one, so in my manifest file I specified that permission.
I'm going crazy with this issue, please help!
Thanks in advance.
EDIT:
Sorry guys, I'm kinda new to this way of asking, and also, not an English native speaker :P
The output I receive after sending the request, is the HTML of the page that handles logging in into the web app... I need like a json response or something like that to make sure the request was saved correctly
Try handling your cookies
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
This should be a singleton.