Consuming Web service from Android Application - android

I am a beginner on Android app development. I want to confirm if my approach is correct and as per best practices in Android world.
I have an android application that needs textual data (no graphic, video). The data comes from REST based web service as JSON string. I consume this web service using HttpGet object, parse json string using JSONArray and display data.
All this happens in a button click.
My questions are:
Is there a better (or android-style) approach to do the same?
What is the preferred approach to retrieve and post graphic contents to REST based web service?
Any help is most appreciated.
Thanks

Please find my inline commnets,
All this happens in a button click.
My questions are:
Is there a better (or android-style) approach to do the same?
Ideal approach to trigger the Webservice calls in Async task or in a service, so your UI thread will not be blocked till HTTP fires and get the response.
What is the preferred approach to retrieve and post graphic contents to REST based web service?
The graphics content will be usually base64 when you try to retrieve it from the backend.
Refer this example : http://androidtrainningcenter.blogspot.in/2012/03/how-to-convert-string-to-bitmap-and.html
for the posting the graphics to the server
I'm going to assume that you know the path and filename of the image that you want to upload. Add this string to your NameValuePair using image as the key-name.
Sending images can be done using the HttpComponents libraries. Download the latest HttpClient (currently 4.0.1) binary with dependencies package and copy apache-mime4j-0.6.jar and httpmime-4.0.1.jar to your project and add them to your Java build path.
You will need to add the following imports to your class.
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
Now you can create a MultipartEntity to attach an image to your POST request. The following code shows an example of how to do this:
public void post(String url, List nameValuePairs) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int index=0; index < nameValuePairs.size(); index++) {
if(nameValuePairs.get(index).getName().equalsIgnoreCase("image")) {
// If the key equals to "image", we use FileBody to transfer the data
entity.addPart(nameValuePairs.get(index).getName(), new FileBody(new File (nameValuePairs.get(index).getValue())));
} else {
// Normal string data
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
} catch (IOException e) {
e.printStackTrace();
}
}
Hope this helps!

Hey refer this link which will train you better in parsing json data as you required in Android App. Loading the graphic required some lazy loading mechanism which you can refer it from here.

Related

How to execute RESTful POST requests from Android

I'm trying to execute a REST Post for the first time and I don't quite know where to begin.
I'm interacting with the WordPress REST API, and am trying to utilize this endpoint: /sites/$site/posts/$post_ID/replies/new, which is used to submit a new comment to a certain post.
I think I have a good grasp on working with GET requests, as I've successfully handled several of them. With those, I could say everything I needed to say to the server vis a vis the URL, but it seems there must be another step with POST requests. And my question is: What is that step(s)?
Do I wrap the content I want to submit into a JSONObject and post that? If so, how do I post it? Do I need to construct a statement somehow, similar to how I would construct a statement to execute on a database? Or is it indeed possible to pass my content along via the URL, as request parameters?
I'm aware that this question is a little on the open-ended side for SO, but I've been unable to find a good tutorial that answers these questions. If you know of one, please suggest it.
(I'm doing this all in an Android app)
My answer is taken straight from another answer on SO seen here Sending POST data in Android but ive cut and past the answer here for conveneience, Hope this helps
Http Client from Apache Commons is the way to go. It is already included in android. Here's a simple example of how to do HTTP Post using it.
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
You need to implement a script on your server, your POST interacts with that script and inturn that script works with your database.
A typical scenario will be:
Java HTTP POST ~~~> PHP ~~~~> MySql.
A good starting point to learn PHP will be to checkout PHPAcademy tutorials on youtube.
http://www.youtube.com/course?list=EC442FA2C127377F07
PHP will as well help you encode the result in JSON and post it back to your client.

Can I send a Android HttpGet (not HttpPost) with 1 string param?

Im coding a RESTful API & Android client at the same time as I go and im currently working on pulling the users profile from the server. I feel like this should definitely be a get request being that im only pulling existing data and im not adding/editing anything to my database, but I do need a user_id param to be able to query for the appropriate profile. Can I send just one tiny little variable along with my HttpGet some how or am i supposed to use a HttpPost in this situation regardless?
Android uses Apache's HTTPClient. So, copying their tutorial code:
public void sendStringTo(String remoteUrl, String myString) {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(remoteUrl+"?string1="+myString);
HttpResponse response1 = httpclient.execute(httpGet);
// The underlying HTTP connection is still held by the response object
// to allow the response content to be streamed directly from the network socket.
// In order to ensure correct deallocation of system resources
// the user MUST either fully consume the response content or abort request
// execution by calling HttpGet#releaseConnection().
try {
System.out.println(response1.getStatusLine());
HttpEntity entity1 = response1.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity1);
} finally {
httpGet.releaseConnection();
}
return;
}
GET can support adding variables/parameters. For example you could make a Url that looks like this:
http://yourwebsite.com/script.php?user_id=19898424

Http Put Request

I am using the HttpPut to communicate with server in Android, the response code I am getting is 500.After talking with the server guy he said prepare the string like below and send.
{"key":"value","key":"value"}
now I am completely confused that where should i add this string in my request.
Please help me out .
I recently had to figure out a way to get my android app to communicate with a WCF service and update a particular record. At first this was really giving me a hard time figuring it out, mainly due to me not knowing enough about HTTP protocols, but I was able to create a PUT by using the following:
URL url = new URL("http://(...your service...).svc/(...your table name...)(...ID of record trying to update...)");
//--This code works for updating a record from the feed--
HttpPut httpPut = new HttpPut(url.toString());
JSONStringer json = new JSONStringer()
.object()
.key("your tables column name...").value("...updated value...")
.endObject();
StringEntity entity = new StringEntity(json.toString());
entity.setContentType("application/json;charset=UTF-8");//text/plain;charset=UTF-8
entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
httpPut.setEntity(entity);
// Send request to WCF service
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(httpPut);
HttpEntity entity1 = response.getEntity();
if(entity1 != null&&(response.getStatusLine().getStatusCode()==201||response.getStatusLine().getStatusCode()==200))
{
//--just so that you can view the response, this is optional--
int sc = response.getStatusLine().getStatusCode();
String sl = response.getStatusLine().getReasonPhrase();
}
else
{
int sc = response.getStatusLine().getStatusCode();
String sl = response.getStatusLine().getReasonPhrase();
}
With this being said there is an easier option by using a library that will generate the update methods for you to allow for you to update a record without having to manually write the code like I did above. The 2 libraries that seem to be common are odata4j and restlet. Although I haven't been able to find a clear easy tutorial for odata4j there is one for restlet that is really nice: http://weblogs.asp.net/uruit/archive/2011/09/13/accessing-odata-from-android-using-restlet.aspx?CommentPosted=true#commentmessage
Error 500 is Internal Server error. Not sure if this answers your question but I personally encountered it when trying to send a data URI for an animated gif in a PUT request formatted in JSON but the data URI was too long. You may be sending too much information at once.

Programmatically filling in a website form using MultipartEntity

I'm taking a mobile development class, which focuses on Android, and for my term project I thought it would be cool if I made a little application that returns a list of cancer-related events and fundraisers. Basically what I have to do is programmatically fill in a webform given criteria that is input from my application, and parse the returned results to give a list of events, because for some reason the American Cancer Society doesn't keep a public list of all events. This is my first real experience with android, and I have almost zero experience with network programming. If I really wanted to, I could just change the URL I go to based on the paramaters given to me, because the ACS event search URLs all look almost exactly the same, but I want to do it "right". I looked at this post and this one for guidance, which led me to the MultipartEntity. They've been very helpful, but I really am not sure what to do next. Code is below:
//Base case, creates entity based on Entered ZIP Code
public void sendRequest()
{
EditText MyEditText = (EditText)findViewById(R.id.zip_edit_text);
String ZIP = MyEditText.getText().toString();
HttpClient defaultClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.cancer.org/Involved/Participate/app/event-search");
try{
MultipartEntity entity = new MultipartEntity();
entity.addPart("ZIP",new StringBody(ZIP));
httppost.setEntity(entity);
HttpResponse response = defaultClient.execute(httppost);
HttpEntity result = response.getEntity();
InputStream stream = result.getContent();
String s = new Scanner(stream).useDelimiter("\\A").next();
Intent intent = new Intent(HomeScreen.this, ListResults.class);
startActivity(intent);
AlertDialog dialog = new AlertDialog.Builder(this).create();
dialog.setMessage(s);
dialog.show();
}catch (ClientProtocolException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
It's pretty bare-bones right now, as you can see. The AlertDialog is used just to see what the HttpResponse looks like, and it seems like it does the POST correctly, and the ZIP code ends up in the right text field, but it doesn't actually "click" the search button. Personally, I think either:
1.) My HttpPost object's URL was incorrect
2.) I used POST instead of GET, or i should POST then GET
I really have tried to work this out myself, and have searched StackOverflow, but I've really come to a rough patch, and as I said before, my network programming experience is near nonexistent. Any help would be appreciated.
I would suggest that you do a printout the URL that was sent through your multipart method, do a search via the web browser, and see if both URL matches. If the URL doesn't match, it means that there's something wrong while setting your entity, etc.

Uploading images to a PHP server from Android

I need to upload an image to a remote PHP server which expects the following parameters in HTTPPOST:
*$_POST['title']*
*$_POST['caption']*
*$_FILES['fileatt']*
Most of the internet searches suggested either :
Download the following classes and trying MultiPartEntity to send the request:
apache-mime4j-0.5.jar
httpclient-4.0-beta2.jar
httpcore-4.0-beta3.jar
httpmime-4.0-beta2.jar
OR
Use URLconnection and handle multipart data myself.
Btw, I am keen on using HttpClient class rather than java.net(or is it android.net) classes. Eventually, I downloaded the Multipart classes from the Android source code and used them in my project instead.
Though this can be done by any of the above mentioned methods, I'd like to make sure if these are the only ways to achieve the said objective. I skimmed through the documentation and found a FileEntity class but I could not get it to work.
What is the correct way to get this done in an Android application?
Thanks.
The Android source seems to come with an internal multipart helper library. See this post. At a quick glance, it's better documented than plenty of public APIs (cough cough, SoundPool, cough cough), so it should be a pretty good place to start, or possibly fine to just use a drop-in solution.
Maybe this post on the official Android group helps. The guy is using mime4j.
Another helpful resource could be this example in the Pro Android book.
I do exactly that to interact with an image hosting server (implemented also in php) that expects parameters as if they were posted from an html page.
I build a List<NameValuePair> of my keys and values something like this:
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair(key1, value1));
params.add(new BasicNameValuePair(key2, value2));
and then I pass it to my http helper class that sets the HttpEntity property of my HttpPost request. Here's the method straight out of my helper class:
public static HttpResponse Post(String url, List<NameValuePair> params, Context context)
{
HttpResponse response = null;
try
{
HttpPost request = new HttpPost();
request.setURI(new URI(url));
if(params != null)
request.setEntity(new UrlEncodedFormEntity(params));
HttpClient client = ((ApplicationEx)context.getApplicationContext()).getHttpClient();
response = client.execute(request);
}
catch(Exception ex)
{
// log, etc
}
return response;
}

Categories

Resources