Android: Get XML from URL with HTTPClient - java

I am trying to get an XML document from URL. I know I should not do this on the UI thread, so I start a new one:
Thread t = new Thread(new GetXML());
t.start();
This starts the inner class GetXML which implements Runnable.
private class GetXML implements Runnable {
#Override
public void run() {
String xmlString = getXmlFromUrl(<URL of the XML as String>);
Document xmlDoc = getDomElement(xmlString);
String textValue = getTextValue(pointWhereItBreaks, xmlDoc, "movie");
}
}
As you can see, this executes a few methods, but the problem is already in the first one getXmlFromUrl:
public String getXmlFromUrl(String xmlUrl) {
String xmlString = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(xmlUrl);
//the following line causes the problem
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xmlString = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return xmlString;
}
I have located the line where it breaks. It doesn't pass the following line:
HttpEntity httpEntity = httpResponse.getEntity();
Does anybody can tell me how to fix the code? I am stuck at this problem for days. I am able to get XML documents by a URL when I run a java application from my computer with a similar code. Why does it not work with Android?
Thank you very much!

Related

Uploading JSONObject to Iris CouchDb in Android

I´m currently working on an app and having my problems with uploading a JSONObject to my Iris CouchDb. But I can´t get it to work.
This is the code I´m using right now:
private class MyHttpPost extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... arg0)
{
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
HttpClient httpClient = new DefaultHttpClient(params);
HttpPost httpPost = new HttpPost("https://dbname.iriscouch.com/dbname");
try {
// Add your data
JSONObject jsonDoc = new JSONObject();
try {
jsonDoc.put("name", "test");
jsonDoc.put("autor", "test author");
jsonDoc.put("rundgangnr", "1");
jsonDoc.put("latitude", 58.0);
jsonDoc.put("longitude", 7.88);
} catch (JSONException e) {
e.printStackTrace();
} // end try
String body = jsonDoc.toString();
StringEntity entity = new StringEntity(body, "utf-8");
httpPost.setEntity(entity);
// Execute HTTP Post Request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
InputStream result = httpEntity.getContent();
} catch (IOException e) {
// TODO Auto-generated catch block
}
return true;
}
}
In onCreate I do this to execute the function:
new MyHttpPost().execute();
When I run the app, there are no errors but nothing gets uploaded. So there isn´t any change in the database.
Am I using the wrong URL to upload it on Iris or is there something wrong with the code? I´m new to Android development and really would appreciate your help as I have been struggling with this for days now.
Perhaps you need to use https://accountname.iriscouch.com/dbname rather than https://dbname.iriscouch.com/dbname.
Also, if the request throws an IOException, your app will be silently swallowing the error so you might not be seeing it.

How can I view the full URL after using MultipartEntityBuilder?

I am fairly confident this code works (I used it in another part of my project for a different API) as far as posting but I do not think the URL is being formatted correctly. I want to know if there is anyway to view the full URL after building all of the entities so I can see if the final URL is formatted correctly. Code:
My URL = http://pillbox.nlm.nih.gov/PHP/pillboxAPIService.php
Method = POST
API key = not going to post (works though)
drugName = just a string that has the name of a drug
I have logs in the code to try and view the url but they aren't returning anything close and the debugger isn't either.
I am trying to build the URL to look like this:
http://pillbox.nlm.nih.gov/PHP/pillboxAPIService.php?key=My_API_KEY&ingredient=diovan
public String makeServiceCallPillBox(String url, int method,
String api, String drugName)
{
String resultEnitity = null;
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = null;
HttpEntity entityResult = null;
// Checking http request method type
if (method == POST)
{
HttpPost httpPost = new HttpPost(url);
// Butild the parameters
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addTextBody("key", api);
builder.addTextBody("ingredient", drugName);;
final HttpEntity entity = builder.build();
httpPost.setEntity(entity);
Log.d("url", httpPost.toString());
httpResponse = httpClient.execute(httpPost);
Log.d("post", builder.toString());
Log.d("post2", entity.toString());
entityResult = httpResponse.getEntity();
resultEnitity = EntityUtils.toString(entityResult);
Log.d("result", resultEnitity);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return resultEnitity;
}
Any help is appreciated.

How to replace  in string java

When i download xml from web,  appends to my xml.
How can i replace it from string. I know i can do it using
substring. but is there a regex expression to do this..
Running code is
XmlParser parser = new XmlParser();
xml = parser.getXmlFromUrl(params[0]);
xml = xml.substring(3);
XmLParse method
public String getXmlFromUrl(String url)
{
String xml = null;
try
{
//default http client
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
System.out.println("URL IN PARSER:==="+url+"====");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpentity = httpResponse.getEntity();
xml = EntityUtils.toString(httpentity);
Log.d("response", xml);
}
catch(UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return xml;
}
 is the BOM in utf-8. Try this:
xml = EntityUtils.toString(entity, "utf-8");

I have to close app and open again for android file upload to work

I have an Android application that records an audio file and uploads it to an API for fingerprinting. The app works well when it uploads for the first time and gets the right response. However, on trying to upload again the request from the app seems to reach the server without the uploaded file. Strangely, when I close the app completely and open it again, it works well. However, I want it to be able to do the uploads continuously without having to close it after every attempt.
Here is my code:
public class MainActivity extends Activity {
class UploadFileTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
String responseString = "";
HttpResponse response = null;
try {
//below is the API url
String url = "http://1**.**.**.**:8000/api/tag/";
File track = new File(Environment.getExternalStorageDirectory(), "mezzo.mp3");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
reqEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fb = new FileBody(track);
//InputStream inputStream = new ;
//reqEntity.addPart("track", fb);
reqEntity.addBinaryBody("track", track);
final HttpEntity myEntity = reqEntity.build();
httppost.setEntity(myEntity);
Log.i("request", String.valueOf(myEntity));
response = httpclient.execute(httppost);
//process response
responseString = new BasicResponseHandler().handleResponse(response);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null!=response)
{
try
{
HttpEntity httpEntity = response.getEntity();
if (null != httpEntity)
{
httpEntity.consumeContent();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return responseString;
}
protected void onPostExecute(final String responseString) {
runOnUiThread(new Thread() {
public void run() {
Toast.makeText(getApplicationContext(),
responseString, Toast.LENGTH_LONG).show();
}
});
}
What I'm I doing wrong?
I am not sure but I suspect that the http response might not be consumed entirely.
Can you try consuming the response before you return from the function in a finally block:
finally
{
if (null!=response)
{
try
{
HttpEntity httpEntity = response.getEntity();
if (null != httpEntity)
{
httpEntity.consumeContent();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

Xml file not received properlly

I am using this code in order to get the rss file from the given url:
// get the xml file from the given url in a string format
public String getXmlFromUrl(String url)
{
String xml = null;
try
{
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
This is the code for getting the xml file text:
String yahoo_url = "http://feeds.finance.yahoo.com/rss/2.0/headline?s=intc&region=US&lang=en-US";
parser = new XMLParser();
String text = parser.getXmlFromUrl(yahoo_url);
System.out.println(text);
Instead of giving me the entire file, I only get two lines:
"?xml version="1.0" encoding="utf-8"?
rss version="2.0"><channel/></rss?"
What may be the problem?
Thanks
The problem may be some encoding issue. If your XML string is processed using the wrong charset, it could be that some characters are misinterpreted as e.g. new lines (would explain the line break in your sample) or End-Of-File.
Try telling EntityUtils the charset of the string (probably UTF-8):
xml = EntityUtils.toString(httpEntity, "UTF-8");

Categories