I download the httpmime.jar from http://www.java2s.com/Code/Jar/h/Downloadhttpmimejar.htm
I put httpmime.jar in the folder of jre7/lib/ext/
It got a error [Multiple markers at this line] on below code
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
Could you give some suggestion? Thanks
My reference android's code as below--------
StringBuffer responseBody = new StringBuffer();
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(
CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost post = new HttpPost("http://IP.IP.IP.IP/file_upload.php");
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("uploadedfile", new FileBody((FileObj), "application/zip"));
post.setEntity(entity);
...
Two things come to mind:
Perform your network on separate thread
make sure the INTERNET permission is set in your Manifest.xml
You should perform long tasks (such as network I/O) in separate thread from the main thread. In fact depending on the version of Android you're developing for, the JVM will raise a NetworkOnMainThreadException if you attempt to do networking on the main thread.
Make sure you are performing your network connection on a separate Thread, as described in this blog post. This is often the cause of weird errors like the one you are probably experiencing. Always make sure you perform potentially expensive operations on a separate Thread (i.e. using an AsyncTask) when developing applications for Android.
Related
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.
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
I'm writing an application for Android. The application connects to a server to retrieve comments.
The code of interest is:
BufferedReader input = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.domain.com/personal_proj/directorydirectory/file.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.i("TEST","after httpclient.execute()");
HttpEntity entity = response.getEntity();
I tested this code in HTC Wildfire, HTC Desire Z and it works. If this code is executed in Android 4.0+, it never reach the line
Log.i("TEST","after httpclient.execute()");
, the server never gets the request and it never throw an exception.
Any ideas?
I'm not sure what the default connection and socket timeout parameters are for the no arg constructed DefaultHttpClient, but I'd check that, or set the params:
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 15000);
HttpConnectionParams.setSoTimeout(params, 20000);
Then construct your HttpClient with the params:
new DefaultHttpClient(params)
At that point you should at least get the timeout, if no other response.
Also look at AndroidHttpClient (it sets up reasonable timeouts, among other things like gzip support), and consider the advice to prefer HttpUrlConnection (though there are caveats with that).
Thanks to Charlie Collins i have noticed that i have not handled well the exception. The exception that i captured it's android.os.NetworkOnMainThreadException. This means that i can't perform a networking operation on the main thread (this is thrown for applications targeting 3.0+). Using AsyncTask worked for me.
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.
I've got the content from a HttpClient, but I'm not sure where to go next, in order to parse my JSON result. Also, how do I do this asynchronously so that I can display a wait dialog to the user with the option of cancelling the current request (not bothered about the UI example, how do I setup the HTTP class to be cancellable)?
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://mysite/test.json");
try
{
HttpResponse response = client.execute(request);
// What if I want to cancel now??
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
}
Android has a class specifically for this sort of thing: AsyncTask.
See the answer to this question: How to create Http Connection using AsyncTask class?
I'm not a Android programmer but I imagine you need to start a thread.
http://download.oracle.com/javase/tutorial/essential/concurrency/