How to fetching content from an URL and parse json - android

I have 2 TextViews in my layout with id's (matricula, nome) and i need get this values from this json request.
I have difficults in both make json request as in get values, here is an example how would i do in php and jquery:
PHP
$alunos = json_decode("let's pretend json data is here");
echo "Matricula: " . $alunos['Aluno']['matricula'];
echo "Nome: " . $alunos['Aluno']['nome'];
Jquery
var alunos = $.parseJSON("let's pretend json data is here");
console.log("Matricula: " + alunos.aluno.matricula);
console.log("Nome: " + alunos.aluno.nome);
To help:
Aluno = Student
Matricula = Student id
Nome = name
I read some answers here about parsing json but i admit it, its hard to understand.

It is also easy in Java (I left out all error handling to focus on the main flow, please add that yourself):
import org.json.JSONObject;
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.InputStream;
import java.io.InputStreamReader;
...
private String readString(Reader r) throws IOException {
char[] buffer = new char[4096];
StringBuilder sb = new StringBuilder(1024);
int len;
while ((len = r.read(buffer)) > 0) {
sb.append(buffer, 0, len);
}
return sb.toString();
}
...
// fetch the content from the URL
URL url = new URL("http://..."); // add URL here
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream(), "UTF-8");
String jsonString = readString(in);
in.close();
conn.disconnect();
// parse it and extract values
JSONObject student = new JSONObject(jsonString);
String id = student.getJSONObject("Aluno").getString("matricula");
String name = student.getJSONObject("Aluno").getString("nome");
For details please see the documentation.

Related

how to connect android to restful api

I'm making an app which let people login, sign in, sign up, write something and save it to database.
So I decided to chose Restful Api with Slim Framework. I publish it in my host and test by extension of google chrome call Advanced Rest Client. Everything like login ,signin, sign up, wite something, update it, delete it.. work fine.
For example:
I log in with information:
email: stark#gmail.com
password: abc
then the result is something like that.
{
error: false
name: "Kien"
email: "nguyenkien1402#yahoo.com"
apiKey: "fc2aee103c861026cb53fd8920b10adc"
createdAt: "2015-06-24 00:28:01"
}
But when I used it in my android app. I cannot connect and get information by JSON.
Please tell my how to solve this problem.
Thank you.
Sorry about my english, it's not native english.
To connect to the restful API, the following steps you have to do
give internet access
have to do http connection
have to to take stream input
Give Internet Access
to give internet access to the app we have to add this piece of code in the file " AndroidManifest.xml"
<uses-permission android:name="android.permission.INTERNET"/>
To do the second and third step we have to create a new java class as when we are connecting to the restful API, it will run in the background and MainActivity does not allow the background task.
Let say we create a new java class "fetchData" to get data from the API.
to do the remaining task we have to use this piece of code
URL url = new URL(API ADDRESS);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
now you get the JSON file using the "Bufferedreader.readLine()"
then the class file looks like this
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class fetchData extends AsyncTask<Void,Void,Void> {
String data ="";
String dataParsed = "";
String singleParsed ="";
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("https://api.myjson.com/bins/k3p10");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
JSONArray JA = new JSONArray(data);
for(int i =0 ;i <JA.length(); i++){
JSONObject JO = (JSONObject) JA.get(i);
singleParsed = "Name:" + JO.get("name") + "\n"+
"email:" + JO.get("email") + "\n"+
"Error:" + JO.get("error") + "\n";
dataParsed = dataParsed + singleParsed +"\n" ;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
from the JSON array, you can extract everything from the JSON you get from the API. then you can use the information as per your requirement.
If your url is generating json response, then you have to read that.
public static String sendGet(String url) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString(); //here is your response which is in string type, but remember that the format is json.
}
Then convert your response to json:
JsonObject obj = new JsonObject(response);
I solved it.
It up to my class about CRUD JSON.
Thank you.

Parsing FlightRadar24 and JSOUP

Hi guys i want parse a flight on flightradar24.com
I have tried with JSOUP and Android but results is null.
http://postimg.org/image/6hdmp4hgv/
I have read... JSOUP doesn't support dinamyc webpages.
There is a solution for this?
I want get Latitude, longitude, and more
Thank you in advance!
In this site the flight details are polled via JavaScript ajax calls. So after page load they invoke an ajax call to http://db8.flightradar24.com/zones/full_all.js?callback=pd_callback&_=1401126256649 to get the flight details. If we zoom into a particular part it uses a separate JavaScript file, say for Europe they use europe_all.js. This essentially returns a json containing all flights details including the speed the altitude etc. this is maintained as a key-value pair and key being the flight id and value an array of details.
First we need to get this json and then parse it to get flight id which is the key and then again invoke http://bma.fr24.com/_external/planedata_json.1.4.php?f=36c0ad6&callback=flight_data_service_cb&_=1401126256666 to get the details flight trails, the name start time, end time, status etc.. The trails is given as an array of latitude and longitude and the first two elements points the current position.
For both url the ending digit is the System.currentTimeMillis();. For the second url the argument "f" is actually the flight ID which is the key of first json. So the below program will parse these two json and give you the data.
I used full_all.js which gives all the flight information which is really huge. To limit the network call i put a break in the for loop. So this program only prints the details of first flight. If you remove the break you'll get all details of all flights but mid you that's like a 10000 calls.
The first json itself gives you enough information like the one given below. Its just one entry from first json and it says flight with id "36c0ae5", the registered key "0D05AD", current lat (25.54), lon (-99.24), speed 287, altitude 16650 ft, etc etc
"36c0ae5": [
"0D05AD",
25.54,
-99.24,
287,
16650,
354,
"0610",
"F-KBRO1",
"A320",
"XA-BIC",
1401129559,
"CUN",
"MTY",
"4O321",
0,
-1920,
"AIJ321",
0
]
Program
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map.Entry;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class FlightDetails {
public static void main(String[] args) throws Exception {
String allFlightsURL = "http://db8.flightradar24.com/zones/full_all.js?callback=pd_callback&_=" + System.currentTimeMillis();
String allFlightsJsonString = getJsonString(allFlightsURL);
JsonParser parser = new JsonParser();
JsonObject allFlightsJsonData = (JsonObject)parser.parse(allFlightsJsonString);
String singleFlightUrl = "http://bma.fr24.com/_external/planedata_json.1.4.php?f=###&callback=flight_data_service_cb&_=";
for(Entry<String, JsonElement> allFlightEntry : allFlightsJsonData.entrySet()){
StringBuilder urlBuilder = new StringBuilder(singleFlightUrl.replaceAll("###", allFlightEntry.getKey())).append(System.currentTimeMillis());
System.out.println(allFlightEntry.getKey() + " = " + allFlightEntry.getValue());
String singleFlightJsonString = getJsonString(urlBuilder.toString());
JsonObject singleFlightJsonData = (JsonObject)parser.parse(singleFlightJsonString);
for(Entry<String, JsonElement> singleFlightEntry : singleFlightJsonData.entrySet()){
System.out.println(singleFlightEntry.getKey() + " = " + singleFlightEntry.getValue());
}
break; // Breaking to avoid huge network calls.
}
System.out.println("Done");
}
private static String getJsonString(String allFlightsURL) throws IOException {
HttpURLConnection connection = (HttpURLConnection) ((new URL(allFlightsURL).openConnection()));
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestMethod("GET");
connection.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder buffer = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.substring(buffer.indexOf("(") + 1, buffer.lastIndexOf(")"));
}
}
you might want to read in the forum:
http://forum.flightradar24.com/threads/24-API-access

How to parse an xml stored in a string variable ?where we get xml response from a webservice which has authentication?

Im not sure whether its a clear question or not.What i want is to retrieve xml response from a webservice.I have the url,username,password,xml body etc details of the webservice.And i could get the xml response in a string variable.Can some one provide me a useful link to parse an xml string? Im sharing the code for retrieving xml
Note:-Make sure you have
commons-httpclient-3.1,commons-codec-1.6,commons-logging-1.1.1,junit-4.10 libraries
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.PostMethod;
public class AbstractService
{
#SuppressWarnings( "deprecation" )
protected String postForString( final String requestUrl, final String requestBody )
{
final StringBuilder result = new StringBuilder();
HttpClient client = new HttpClient();
try
{
PostMethod postRequest = new PostMethod( getAbsoluteUrl( requestUrl ) );
postRequest.addRequestHeader( WebServiceClientConstants.CONTENT_TYPE,
WebServiceClientConstants.APPLICATION_XML );
postRequest.setRequestBody( WebServiceClientConstants.REQUEST_HEADER + requestBody );
client.getState()
.setCredentials(
new AuthScope( WebServiceClientConstants.HOST, WebServiceClientConstants.PORT,
AuthScope.ANY_REALM ),
new UsernamePasswordCredentials( WebServiceClientConstants.USERNAME,
WebServiceClientConstants.PASSWORD ) );
int responseCode = client.executeMethod( postRequest );
System.out.println( "[REQUEST][" + postRequest.getURI().toString() + "]" );
System.out.println( "[STATUS][" + postRequest.getStatusLine().toString() + "]" );
if ( HttpStatus.SC_OK == responseCode )
{
String data = null;
final InputStream responseStream = postRequest.getResponseBodyAsStream();
final BufferedReader bufferedReader = new BufferedReader( new InputStreamReader( responseStream,
WebServiceClientConstants.UTF_8_ENCODING ) );
while ( ( data = bufferedReader.readLine() ) != null )
{
result.append( data );
}
}
postRequest.releaseConnection();
}
catch ( Exception e )
{
e.printStackTrace();
}
return result.toString();
}
private String getAbsoluteUrl( String requestUrl )
{
return WebServiceClientConstants.SERVIE_BASE_URL + requestUrl;
}
}
WebServiceClientConstants interface
package com.test.service.info;
public interface WebServiceClientConstants
{
String PROTOCOL = "http://";
String HOST = "youraddress.blah.test.com";
Integer PORT = 8080;
String SERVIE_BASE_URL = "http://youraddress.blah.test.com:8080/test/seam/resource/Services/";
String USERNAME = "Username";
String PASSWORD = "password";
String REQUEST_HEADER = "<?xml version=\"1.0\"?>";
String CONTENT_TYPE = "Content-Type";
String APPLICATION_XML = "application/xml";
String UTF_8_ENCODING = "UTF-8";
}
MenuService interface
public interface MenuService
{
String getMenu();
}
MenuServiceImpl.java
public class MenuServiceImpl extends AbstractService implements MenuService
{
#Override
public String getMenu()
{
String requestUrl = "getMenu";
String requestBody = "<ServiceRequest>" + "<ShortName>AppName</ShortName>"
+ "</ServiceRequest>";
return postForString( requestUrl, requestBody );
}
}
Then a in some activity write
MenuService menuService = new MenuServiceImpl();
String prMenu = menuService.getMenu();
Assert.assertNotNull( prMenu );
test.setText(prMenu);
Now i have the xml response with me stored in prMenu variable.And it will look like this
http://www.coders-global.com/works/dev/menuserivicetemp.xml.Now how can i parse this Xml string.Please take a took look at the link.It looks complex and i had asked how to parse this link before in some other thread and the replies were not that helpful.If any have useful links or suggestions please tell.
Your question seems to amount to 'How do I parse XML content stored in memory' as you seem able to grab the data correctly from the remote server.
Essentially there are two tools for this built into Java libraries called the SAX and DOM parsers respectively. These two options work quite differently and it is important that you understand the differences and choose intelligently between them.
Here is an example of using the DOM parser in android XML Parsing Tutorial which is probably the direction you want to take given the low volume of the data.
PS: also using String.append as you do is pretty bad from a performance point of view - you need to look at the stringbuilder classes that are optimised for this kind of task.

Parse incoming http post request java android

I am working on an Android web server.When i go to localhost:8080 on the emulator browser, it serves a page/form with a password field. On successful verification of the password, I would like to redirect the user to the success/failure page.What would be the best way to read the incoming http post request and parse the password field for verification?Any pointers in the right direction would be greatly appreciated. I have a handler for the url to which the form is submitted. The code for the handler is:
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.entity.ContentProducer;
import org.apache.http.entity.EntityTemplate;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import android.content.Context;
public class LoginHandler implements HttpRequestHandler {
private Context context = null;
public LoginHandler(Context context) {
this.context = context;
}
#Override
public void handle(final HttpRequest request, HttpResponse response,
HttpContext httpcontext) throws HttpException, IOException {
HttpEntity entity = new EntityTemplate(new ContentProducer() {
public void writeTo(final OutputStream outstream) throws IOException {
String resp = null;
OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
if(validatePassword()==true){
resp ="<html><head></head><body><h1>Home<h1><p>Success.</p></body></html>";
}
else{resp="<html><head></head><body><h1>Home<h1><p>Login Failed.</p></body></html>";}
writer.write(resp);
writer.flush();
}
});
response.setHeader("Content-Type", "text/html");
response.setEntity(entity);
}
boolean validatePassword(){
boolean pass=false;
//parse request body here and check for the password if true return true/else false
return pass;
}
}
After looking around for ages I found the solution. Adding the following in the handle method does the trick.Thanks to the original poster
.http://www.androiddevblog.net/android/a-bare-minimum-web-server-for-android-platform
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
if (entity != null) {
Log.v("RequestBody", EntityUtils.toString(entity, "UTF-8"));
entity.consumeContent();
}
}
I apologize if this isn't quite what you're asking, so if it's not, let me know.
You could use a JSONObject to return whether or not that password was verified as correct.
For example, if the password is correct, you could store the HTTP result as:
{"status":200,"confirmed":"true"}
Or "false" otherwise.
When you get back from the HTTP Post Request, you can store this result as a String, then make a JSONObject out of it. For example:
// Send the URL to a postRequest function and return the result as a String
String output = makePostRequest(url);
// Parse the String as a JSONObject and receive whether or not the login was confirmed
JSONObject o = new JSONObject(output);
String confirmed = o.getString("confirmed");
if (confirmed.equals("true")) {
// Password confirmed - redirect user to success page
} else {
// Password incorrect - redirect user to failure page
}
Note: in case you need an idea of how to receive the response code from the post request, here's some sample code:
String output = {};
// Use bufferedreader and stringbuilder to build an output string (where conn is your HTTPUrlConnection object you used to make the post request
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
// Loop through response to build JSON String
while((line = br.readLine()) != null) {
sb.append(line + "\n");
}
// Set output from response
output = sb.toString();
And now output is the String you can turn into a JSONObject.
Does any of this help?
Edit:
Okay, so the String you will be getting will be in the format of {"password":"somepassword"}. To parse this, try this out:
String s = /* the string in the format {"password":"somepassword"} */
JSONObject o = new JSONObject(s);
String password = o.getString("password");
if (password.equals(random_password_at_beginning_of_webservice) {
// Password confirmed - redirect user to success page
} else {
// Password incorrect - redirect user to failure page
}

Should i have to set proxy for consuming web services in android?

I am working on a computer that is joined with server in LAN.proxy is used to access internet in my computer, now i am doing project on consuming php web services which give JSON as output.i have made a app for it but it gives blank response,i have read one of the stack overflow question answer that say that it is because of proxy.
should i have to set proxy setting in my application.
And how can i set proxy for this problem.
i have set the proxy by this step
Click on Menu
Click on Settings
Click on Wireless & Networks
Go to Mobile Networks
Go to Access Point Names
Here you will Telkila Internet, click on it.
In the Edit access point section, input the "proxy" and "port"
Also provide the Username and Password, rest of the fields leave them blank
internet is working in emulator,but still project display nothing.
this is my code
package com.example.jsonexaple2;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
public class Jsonexaple2 extends Activity {
String archiveQuery = "http://www.archive.org/advancedsearch.php?q=Lotus&fl[]=date&fl[]=format&fl[]=identifier&fl[]=mediatype&fl[]=title&sort[]=createdate+desc&sort[]=&sort[]=&rows=10&page=1&output=json&callback=callback&save=yes";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jsonexaple2);
InputStream in = null;
String queryResult = "";
try {
URL url = new URL(archiveQuery);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.connect();
in = httpConn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int read = 0;
int bufSize = 512;
byte[] buffer = new byte[bufSize];
while(true){
read = bis.read(buffer);
if(read==-1){
break;
}
baf.append(buffer, 0, read);
}
queryResult = new String(baf.toByteArray());
} catch (MalformedURLException e) {
// DEBUG
Log.e("DEBUG: ", e.toString());
} catch (IOException e) {
// DEBUG
Log.e("DEBUG: ", e.toString());
}
JSONObject jObject;
try {
jObject = new JSONObject(queryResult.replace("callback(", "")).getJSONObject("response");
JSONArray docsArray = jObject.getJSONArray("docs");
for (int i = 0; i < 10; i++) {
if (docsArray.getJSONObject(i).optString("mediatype").equals("etree")) {
String title = docsArray.getJSONObject(i).optString("title");
String identifier = docsArray.getJSONObject(i).optString("identifier");
String date = docsArray.getJSONObject(i).optString("date");
System.out.println(title + " " + identifier + " " + date);
}
}
} catch (JSONException e) {
// DEBUG
Log.e("DEBUG: ", e.toString());
}
}
}
Yes you have to. Once, I had the same problem with the emulator. I searched on Google and I found these two blogs that are nice.
gitshah
twozao
Hope that it will help you.

Categories

Resources