Http Put Request - android

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.

Related

Consuming Web service from Android Application

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.

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

EntityUtils reports NoApplicableCode exception for Android request

I am trying to retrieve a JSON file from a web service using the following URL. That works fine when I use a browser to send the HTTP request.
For the Android application I came up with the following code.
// Android request
String url = "http://data.wien.gv.at/daten/geoserver/ows?service=WFS" +
"&request=GetFeature&version=1.1.0&typeName=ogdwien:BAUMOGD" +
"&srsName=EPSG:4326&outputFormat=json" +
"&bbox=16.377681,48.211448,16.379829,48.21341,EPSG:4326" +
"&maxfeatures=10"
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
Though, EntityUtils does not output a JSON file but this XML exception.
// Value of result
<?xml version="1.0" encoding="UTF-8"?>
<ows:ExceptionReport version="1.0.0"
xsi:schemaLocation="http://www.opengis.net/ows http://data.wien.gv.at/daten/geoserver/schemas/ows/1.0.0/owsExceptionReport.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ows="http://www.opengis.net/ows">
<ows:Exception exceptionCode="NoApplicableCode">
<ows:ExceptionText>java.io.EOFException: input contained no data
input contained no data</ows:ExceptionText>
</ows:Exception>
</ows:ExceptionReport>
I hope you can see what wents wrong ...
The HTML specifications technically define the difference between "GET" and "POST" so that former means that form data is to be encoded (by a browser) into a URL while the latter means that the form data is to appear within a message body. > [source]
Since you do encode the full request into the URL (request=GetFeature etc.) => use HttpGet instead.
Might even work imo with post since the url should still be transmitted to the server but the server would need to detect that the post request is actually a get request and behave accordingly.

Android uploading file as ByteArray to WCF REST services

I need to send a byte arrray file using WCF rest services. I have to send the data using HttpPost method in android. The code which i am using give the status as HTTP/1.1 400 Bad Request error.
private final static String URI = "http://192.168.1.15/QueryService/Import/Test";
final HttpPost request = new HttpPost(URI);
final HttpClient httpClient = new DefaultHttpClient();
final ByteArrayEntity entity = new ByteArrayEntity(fileToBytes(pathToOurFile));
entity.setContentType("application/octet-stream");
entity.setChunked(true);
request.setEntity(entity);
final HttpResponse hr = httpClient.execute(request);
final StatusLine status = hr.getStatusLine();
httpClient.getConnectionManager().shutdown();
It is difficult to tell what is wrong with your request. The standard way of resolving this kind of errors is:
Create a WCF client for your service. Verify that it works as expected.
Use Fiddler or another suitable tool to intercept the HTTP request your client is generating. Both the headers and the body are important.
Modify your Android request to generate the exact same request as the WCF client.
I was also facing same problem with WCF service. 400 Bad request means request parameter value which you are passing to method doesn't match with method's parameter. I have used Base64 string encoding to pass file as method parameter. May it'll help you.

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