File upload using MultipartEntityBuilder gives an Error - android

In my android app I'm using AsyncTask to upload a file to the backend. In there I use MultipartEntityBuilder in my doInBackground method. my doInBackground part is as follows,
#Override
protected String doInBackground(String... params) {
try {
String serverLoaction = params[0];
String filePath = params[1];
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(serverLoaction);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fileBody = new FileBody(new File(filePath));
StringBody stringBody = new StringBody("data", ContentType.MULTIPART_FORM_DATA);
builder.addPart("file", fileBody);
builder.addPart("name", stringBody);
httpPost.setEntity(builder.build());
HttpResponse response = httpClient.execute(httpPost, localContext);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
return sResponse;
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Error in downloading image", Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
}
This show me no syntax errors. but when I run the code an exception throws and the app stops. the error log is as below.
Process: com.x.x, PID: 6271
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NoSuchFieldError: org.apache.http.message.BasicHeaderValueFormatter.INSTANCE
at org.apache.http.entity.ContentType.toString(ContentType.java:153)
at org.apache.http.entity.mime.MultipartFormEntity.<init>(MultipartFormEntity.java:56)
at org.apache.http.entity.mime.MultipartEntityBuilder.buildEntity(MultipartEntityBuilder.java:236)
at org.apache.http.entity.mime.MultipartEntityBuilder.build(MultipartEntityBuilder.java:240)
at com.x.x.ui.farm_activity.AddCropMonitors$UploadFileTask.doInBackground(AddCropMonitors.java:1905)
at com.x.x.ui.farm_activity.AddCropMonitors$UploadFileTask.doInBackground(AddCropMonitors.java:1875)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
at java.lang.Thread.run(Thread.java:841)
 
it tells NoSuchFieldError exception raises, but I go through several tutorials and it's seems to me the code is ok according to them. the line number points to where the error occurs is points to
httpPost.setEntity(builder.build());
line. so whats the problem with this code segment and how can I fix this. thanks and regards!

I think this is due to library which you are using in your build.gradle file.
Please check with below code once
compile('org.apache.httpcomponents:httpmime:4.3.6') {
exclude module: 'httpclient'
}
compile 'org.apache.httpcomponents:httpclient-android:4.3.5'

add this in your build.gradle file.
implementation 'org.apache.httpcomponents:httpmime:4.5.10'

Related

AsyncTask DoInBackground downloading Google Spreadsheets Data Returning Null?

Here is the code:
#Override
public String doInBackground(String... params)
{
try
{
URL url = new URL("http://spreadsheets.google.com/tq?key=BLAHBLOAHBLAH");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); //Cast HttpUrlConnection because URL does not contain methods available to url, creates object
httpURLConnection.setRequestMethod("GET"); //Request data from source
httpURLConnection.setDoInput(true);
httpURLConnection.connect(); //Object actually connects, connect() invoked by getInputStream() etc.
//Reads data from network stream
InputStream inputStream = httpURLConnection.getInputStream();
//Rather than read one character at a time from the network or disk, BufferedReader reads a larger block at a time
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
//Used to create mutable string e.g. append()
StringBuilder stringBuilder = new StringBuilder();
String line = "";
//Change stream data to StringBuilder data
while ((line = bufferedReader.readLine()) != null)
{
stringBuilder.append(line + "\n");
}
String result = stringBuilder.toString();
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
}
catch(IOException e)
{
e.printStackTrace();
}
return null;
}
I'm basically downloading the JSON data from Google Spreadsheets, but the result returned from the doInBackground function continues to return some sort of a null object reference. What does this mean?...
EDIT*
Here is my logcat:
07-28 12:41:30.289 3796-3891/com.example.steven.app E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
Process: com.example.steven.app, PID: 3796
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.AlertDialog.setMessage(java.lang.CharSequence)' on a null object reference
at com.example.steven.database.DownloadGS.doInBackground(DownloadGS.java:95)
at com.example.steven.database.DownloadGS.doInBackground(DownloadGS.java:49)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
at java.lang.Thread.run(Thread.java:818) 
Picture of what is actually being stored inside String result...
My problem was:
URL url = new URL("http://spreadsheets.google.com/tq?key=BLAHBLOAHBLAH");
I found out that by reading here:
URLConnection Doesn't Follow Redirect
the setFollowRedirect and setInstanceFollowRedirects only work automatically when the redirected protocol is same . ie from http to http and https to https. (Shalvika)
I changed the statement to:
URL url = new URL("https://spreadsheets.google.com/tq?key=BLAHBLOAHBLAH");
Your code looks fine, the problem is that you are not allowed to get data from that URL.
On hitting this URL "http://spreadsheets.google.com/tq?key=BLAHBLOAHBLAH"
I am getting following response, so i guess you are getting access denied from server.
google.visualization.Query.setResponse (
{
"version": "0.6",
"status": "error",
"errors": [
{
"reason": "access_denied",
"message": "Access denied",
"detailed_message": "Access denied"
}]
}
)

Error in adding file to MultipartEntityBuilder in android

In my Android project I'm using MultipartEntityBuilder in uploading files to backend using an AsyncTask. I'm using httpmime-4.5.2 in my project.my doInBackground method in uploading AsyncTask is as below.
#Override
protected String doInBackground(String... params) {
try {
String serverLoaction = params[0];
String filePath = params[1];
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(serverLoaction);
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fileBody = new FileBody(new File(filePath));
entity.addPart("file", fileBody);
HttpEntity entity_ = entity.build();
httpPost.setEntity(entity_);
HttpResponse response = httpClient.execute(httpPost,
localContext);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
return sResponse;
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Error in downloading image", Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
}
but when the AsyncTask is executing it gives me following error.
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NoClassDefFoundError: org.apache.http.entity.ContentType
at org.apache.http.entity.mime.content.FileBody.<init>(FileBody.java:89)
at com.marpak.livefarmerpro.ui.farm_activity.AddCropMonitors$UploadFileTask.doInBackground(AddMonitors.java:1912)
at com.marpak.livefarmerpro.ui.farm_activity.AddCropMonitors$UploadFileTask.doInBackground(AddMonitors.java:1884)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
at java.lang.Thread.run(Thread.java:841)
 
so whats wrong with this code. how can I fix this. Thanks and regards.
Finally I figured out the reason. I've imported httpmime library in to the project. But in my case it need another library to be executed together with httpmime. I import httpcore library and build the project. it solve the problem. :D I just add below line to build.gradle and re build the project.
compile 'org.apache.httpcomponents:httpcore:4.4.4'

android- Intentional '%' in string throws IllegalArgumentException

I am making a http call to an api for a string response.
The result contains intentional % signs in a sentence like:
"This land is 95% fertail and 5% contaminated"
Android throws IllegalArgumentException: Invalid % sequence at 1756 which corresponds to the "95%" part.
EDIT: StackTrace:
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.IllegalArgumentException: Invalid % sequence at 1756: [{"address":{"addressComponen...
My httpGet method:
public String makeHttpGetRequestUtf8(String urlStr) throws IOException {
String result = "";
try {
URL url = new URL(urlStr);
BufferedReader brIn = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
String line = "";
while ((line = brIn.readLine()) != null)
result += line;
}catch (Exception e){
Log.e("HTT_GET", "Failed to make httpGetRequestUtf8: " + e);
}
String afterDecode = URLDecoder.decode(result, "UTF-8");
return afterDecode;
}
Android throws IllegalArgumentException: Invalid % sequence at 1756 which corresponds to the "95%" part.
Server writes this data with this metod and so I believe the encoding should be fine?
File file = new File(path/filename.txt);
String content = writeMeToFile;
Writer out;
try{
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file), "UTF8"));
if(!file.exists()){
file.createNewFile();
}else{
FileUtils.copyFile(file, dest);
out.write(content);
out.close();
}
} catch (IOException e) {
Logger.getLogger(UpdateAds.class.getName()).log(Level.SEVERE, null, e);
}
Side question/note: Somehow characters like 'ä', 'ö', 'ü', 'õ' are fine in the browser but show up as � in android.
I don't understand at which side am I encoding the string wrong. Since the text is fine in the browser I am thinking it's android, but the httpGet method is done by the book.
Thanks!

java.lang.NullPointerException at HttpGet httpGet = new HttpGet(url);

public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
This is the class i use for getting String from REST request
12-26 10:51:35.610 1750-1778/hackerspace.invento.ebooks E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
Process: hackerspace.invento.ebooks, PID: 1750
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at java.net.URI.parseURI(URI.java:353)
at java.net.URI.<init>(URI.java:204)
at java.net.URI.create(URI.java:725)
at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:75)
at hackerspace.invento.ebooks.ServiceHandler.makeServiceCall(ServiceHandler.java:63)
at hackerspace.invento.ebooks.ServiceHandler.makeServiceCall(ServiceHandler.java:39)
at hackerspace.invento.ebooks.Books$GetResult.doInBackground(Books.java:113)
at hackerspace.invento.ebooks.Books$GetResult.doInBackground(Books.java:94)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
and this is the Log Error i get How do i solve this?
My guess would be that you are either passing a NULL string into your method, or for some reason the string is getting set to NULL if the HttpGet() method fails to resolve the URL or something else goes wrong. Try appending this at the end of your try / catch statement:
catch (Exception e)
{
Log.e("MyApp", "exception: " + e.getMessage());
Log.e("MyApp", "exception: " + e.toString());
}
Normally, a statement such as this is poor practice to use in your software, as it will essentially squash any exception you get without allowing you to handle the various exception cases. However, for debugging purposes, adding this statement at the end of you try/catch statement will allow you to see if there is perhaps an exception that you are missing that is causing the HttpGet() method to fail which, in turn, causes your NULL error. If you do detect another exception, you can handle it appropriately so that your method no longer returns a NULL string.
Your url is NULL
URISyntaxException
Throws: java.lang.NullPointerException If either the input or reason strings are null

Android- org.apache.http.ProtocolException: The server failed to respond with a valid HTTP response

I am trying to send a HTTP post request to a REST service through my android app and the client runs as an async task. Here is the client:
#Override
protected Void doInBackground(Void... params) {
String address = "http://xxx.xx.x.xxx:8080/rest/manageUser/create";
StringBuilder stringBuilder = null;
ArrayList<NameValuePair> postParameters;
try {
HttpPost httpPost = new HttpPost(address);
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("userId", userId));
postParameters.add(new BasicNameValuePair("firstName", firstName));
postParameters.add(new BasicNameValuePair("lastName", lastName));
postParameters.add(new BasicNameValuePair("mobileNumber",
mobileNumber));
postParameters.add(new BasicNameValuePair("loginStatus",
loginStatus));
httpPost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpClient client = new DefaultHttpClient();
HttpResponse response;
stringBuilder = new StringBuilder();
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
// System.out.println(stringBuilder);
} catch (Exception e) {
e.printStackTrace();
}
JSONObject jobj = null;
try {
jobj = new JSONObject(stringBuilder.toString());
System.out.println(jobj.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
Also when I create the client as an standalone java class it works fine. But when I use it from my Android app as an async task as above, I get the following exception:
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at com.example.hello.service.client.CreateUser.doInBackground(CreateUser.java:64)
at com.example.hello.service.client.CreateUser.doInBackground(CreateUser.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: org.apache.http.ProtocolException: The server failed to respond with a valid HTTP response
at org.apache.http.impl.conn.DefaultResponseParser.parseHead(DefaultResponseParser.java:93)
at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:174)
at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:180)
at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:235)
at org.apache.http.impl.conn.AbstractClientConnAdapter.receiveResponseHeader(AbstractClientConnAdapter.java:259)
at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:279)
at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:121)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:428)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
... 10 more
org.json.JSONException: End of input at character 0 of
at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
at org.json.JSONTokener.nextValue(JSONTokener.java:97)
at org.json.JSONObject.<init>(JSONObject.java:155)
at org.json.JSONObject.<init>(JSONObject.java:172)
at com.example.hello.service.client.CreateUser.doInBackground(CreateUser.java:82)
at com.example.hello.service.client.CreateUser.doInBackground(CreateUser.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Can anyone suggest what could be the problem. Also in my rest service, I am recieving the data with the #FormParam . Any help would be appreciated.
I think you are using wrong HTTP method. Just check HTTP Method whether it is correct or not and just try to get json that is going as part of request body.

Categories

Resources