I am creating an Android application that connects to the Fogbugz XML API (sends a request to the API, receives back an XML file). Right now, I am creating a service that will handle these requests, and parse each in order to access usable information. What would be the best way to do this? If I am getting an inputStream, should I use the SAX parser?
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("My URL THAT RETURNS AN XML FILE");
HttpResponse response;
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String responseString = "";
String temp;
while ((temp=bufferedReader.readLine()) != null)
{
responseString += temp;
}
if (entity != null) {
entity.consumeContent();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I suggest that you use some XML DOM library like XOM or Dom4j. It will be much easier for you to work with tree structure than with SAX events. Personally, I use XOM in Foglyn -- FogBugz for Eclipse plugin. You can pass InputStream directly to your SAX/XOM/Dom4j parser, there is no need to build string first. Furthermore, make sure you use correct encoding ... your code is broken in this regard. (When you pass InputStream to your parser, this is handled by parser. In XOM you can use new Builder().build(InputStream) method).
One FogBugz API hint ... when getting details about case, and you don't need events (comments), don't fetch them at all. I.e. don't put events into list of columns.
Related
I have an application and I need to get some data from my database(MySQL and it stays on web, not local). I think a simple RestFul webservice will be the best option for me to access this database and get the data. However, I m not able to create the webservice. I did some researches but I got confused. All I need is just accessing the database and get a few data from the table. Please give me some help to create the neccessary webservice. I don't want it to be a complex webservice. Thank to you all
this is php page of web-service. in this userid is taken from android java file that requesting that data. and after that selecting data from mySql it will simply echo all data and that will be given to java file as response.
seluser_profile.php
<?php
//$con=mysql_connect("localhost","root","");
//mysql_select_db("android_db",$con);
$con=mysql_connect("localhost","root","");
mysql_select_db("android_db",$con);
$uname=$_POST['userid'];
$q="select * from user_details where username='$uname'";
$rec=mysql_query($q);
if(mysql_num_rows($rec)==1)
{
$arr=mysql_fetch_array($rec);
echo $arr[0]+" "+$arr[2]+" "+$arr[3];
}
else
{
echo "false";
}
?>
Java code for requesting to web service.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.0.2/webservice/seluser_profile.php");
try {
// Add your data
//Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_LONG).show();
List<NameValuePair> namevpair = new ArrayList<NameValuePair>(2);
namevpair.add(new BasicNameValuePair("userid",valueIWantToSend));//in this first argument is name of post variable which we will use in php web service as name of post varible $_POST['fname'];
httppost.setEntity(new UrlEncodedFormEntity(namevpair));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
str = inputStreamToString(response.getEntity().getContent()).toString();
//Toast.makeText(getApplicationContext(), "your answer="+str, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
use this java code in doInBackground method of Asynctask class. otherwise it will give you network handler exception.
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
and also add this function for string building from inputstream.
Here is a link, You may seen this while surfing, I know this is not an answer , but I cannot comment bcz I dnt have enough Rep.
http://www.androidhive.info/2014/01/how-to-create-rest-api-for-android-app-using-php-slim-and-mysql-day-12-2/
I used this in one of my project, customization was very easy..and a great tutorial.
I'm trying to download a JSON file in this format
[
{
"CRN":"10001",
"Course":"REG1"
},
{
"CRN":"10002",
"Course":"REG2"
}
]
I understand how to use a JSONArray class once it is created but I don't know how to create the JSONArray object from the file. If the URL location of the file were to be "www.test.com" how would I go about downloading it in background upon the launch of my application so as to not interfere with the launching of the app but not require the user to manually download it themselves.
You might want to check out this helpful library: Retrofit
It makes grabbing and parsing JSON data easy!
I think you should look for Android Web Service example. Where you can find info about
1.How to make a HTTP request to server (using URL eg. www.google.com)
2. How to handle Response from Server
3. How to parse JSON/XML response from Server etc.
Here is the Simple Tutorial I Found for you.
Android Web service for Log-in and Registration
Just go through step by step.
In the example we are making request to server for login and getting response then going ahead in app.
Here is the code snipp.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
A good way to download the JSON file automatically, would be to launch an AsyncTask during your onCreate method of the home activity.
JSON files are nothing more than text files in a special format, so the could be easily downloaded as a response from a HttpURLConnection, and then be treated as a String.
A suggestion for parsing the JSON objets into Java objects would be the Jackson JSON Processor. You could use the class ObjectMapper of this library to automatically create the objects.
If you are planing to implement the server side by yourself, and you also need a library to send JSON objects, you could use Jersey on both server and client.
Can anyone tell me which is the best, ease and flexible method to consume web service from android? I'm using eclipse.
Since you only care about consuming a webservice, I assume you already know how to send data from the web server. Do you use JSON or XML, or any other kind of data format?
I myself prefer JSON, especially for Android.
Your question still lacks some vital information.
I personally use apache-mime4j and httpmime-4.0.1 libraries for web services.
With these libraries I use the following code
public void get(String url) {
HttpResponse httpResponse = null;
InputStream _inStream = null;
HttpClient _client = null;
try {
_client = new DefaultHttpClient(_clientConnectionManager, _httpParams);
HttpGet get = new HttpGet(url);
httpResponse = _client.execute(get, _httpContext);
this.setResponseCode(httpResponse.getStatusLine().getStatusCode());
HttpEntity entity = httpResponse.getEntity();
if(entity != null) {
_inStream = entity.getContent();
this.setStringResponse(IOUtility.convertStreamToString(_inStream));
_inStream.close();
Log.i(TAG, getStringResponse());
}
} catch(ClientProtocolException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} finally {
try {
_inStream.close();
} catch (Exception ignore) {}
}
}
I make a request via _client.execute([method], [extra optional params])
The result from the request is put in a HttpResponse object.
From this object you can get the status code and the entity containing the result.
From the entity I take the content. The content would in my case be the actualy JSON string. You retrieve this as an InputStream, convert the stream to a string and do whatever you want with it.
For example
JSONArray result = new JSONArray(_webService.getStringResponse()); //getStringResponse is a custom getter/setter to retrieve the string converted from an inputstream in my WebService class.
Depending on how you build your JSON. mine is nested deeply with objects in the array etc.
But handling this is basic looping.
JSONObject objectInResult = result.getJSONObject(count);//count would be decided by a while or for loop for example.
You can extract data from the current JSON object in this case like:
objectInResult.getString("name"); //assume the json object has a key-value pair that has name as a key.
to parse "JSON" I recommend the following library is the faster and better.
Jackson Java JSON-processor
I wish to settle my long term problem by this question and hope you guys would help, but firstly; I have been having issues to connect to a HTTPS self-signed certificate server for almost 3 weeks. Despite the multiple solutions here, I cannot seem to resolve my problem. Probably I did not know how to use it properly or did not have some files or imported the correct libraries.
I came across some websites that requires me to download a certificate from the https site that I am trying to connect into, and when I did that. I have to do the some steps before I can use the certificate or keystore that I created. I got this solution from this website:
Android: Trusting SSL certificates
// Instantiate the custom HttpClient
DefaultHttpClient client = new MyHttpClient(getApplicationContext());
HttpGet get = new HttpGet("https://www.mydomain.ch/rest/contacts/23");
// Execute the GET call and obtain the response
HttpResponse getResponse = client.execute(get);
HttpEntity responseEntity = getResponse.getEntity();
I have a problem, after the last line, as stated above. What do I do with the responseEntity? How do I use it if I wish to display the https website on a WebView? Some help and explanation would be nice :)
If you want the content from the HttpEntity the correct way does not include calling HttpEntity#getContent() to retrieve a stream and doing tons of pointless stuff already available in the Android SDK.
Try this instead.
// Execute the GET call and obtain the response
HttpResponse getResponse = client.execute(get);
HttpEntity responseEntity = getResponse.getEntity();
// Retrieve a String from the response entity
String content = EntityUtils.toString(responseEntity);
// Now content will contain whatever the server responded with and you
// can pass it to your WebView using #loadDataWithBaseURL
Consider using WebView#loadDataWithBaseURL when displaying content - it behaves a lot nicer.
You need to call responseEntity.getContent() to get response in InputStream against your requested URL. Use that stream in your way to present data as you want. For example, if the expected data is String, so you may simply convert this stream into string with the following method:
/**
* Converts InputStream to String and closes the stream afterwards
* #param is Stream which needs to be converted to string
* #return String value out form stream or NULL if stream is null or invalid.
* Finally the stream is closed too.
*/
public static String streamToString(InputStream is) {
try {
StringBuilder sb = new StringBuilder();
BufferedReader tmp = new BufferedReader(new InputStreamReader(is),65728);
String line = null;
while ((line = tmp.readLine()) != null) {
sb.append(line);
}
//close stream
is.close();
return sb.toString();
}
catch (IOException e) { e.printStackTrace(); }
catch (Exception e) { e.printStackTrace(); }
return null;
}
InputStream is = responseEntity.getContent();
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
String result=sb.toString();
is.close();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
you will have all the content in the String "result"
I need to parse the XML data returned from accessing a REST-based service to display only one single tag. For example, parse the XML data shown below to display firstname tag and value John only.
<company>
<staff>
<firstname>John</firstname>
<lastname>Doe</lastname>
</staff>
</company>
I am struggling to figure out how to interface with the SAX parsing code once XML data is returned by RESTClient. I tried different approaches after learning from different example codes but still cannot figure it out partly because they do not have the same exact purpose. So please kindly teach me how to call/pass the data to the parsing code and what to return from the parsing code, whether the parsing code should be in a separate class, etc. I am basically clueless without some guidance. Relevant RESTClient code is presented below. Thanks!
public class RESTClient {
public static String callRESTService(String url) {
String result = null;
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
InputStream instream = entity.getContent();
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp;
try (
sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
DefaultHandler handler = new DefaultHandler();
xr.setContentHandler(handler);
InputSource is = new InputSource(instream);
xr.parse(is);
//what should/can be returned here from the parsing code:
//String, InputSource, InputStream?. Convert data type?
}
catch (SAXException e)
{
e.printStackTrace();
}
catch (ParserConfigurationException e)
{
e.printStackTrace();
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
)
http://as400samplecode.blogspot.com/2011/11/android-parse-xml-file-example-using.html
You have to extend DefaultHandler and make your own XML handler where you will parse your xml.
You can see the example of extending Defaulthandler in above link.
I insist that you should keep your parser code in separate file . Since RestClient is only responsible for sending and receiving of data from remote location . This is would also provide u lose coupling between the two components .
what to return from the parsing code Output of processor depends on your needs. (Personally i am returning List of HashMap)
I suggest that you return a POJO here.