Reputation: 669
I try to send an image with httppost, here is my code :
private class UploadImageTask extends AsyncTask<String, Void, Integer>
{
private String chemin;
public UploadImageTask(String uri)
{
this.chemin = uri;
}
public Integer doInBackground(String... url)
{
try
{
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url[0]);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("image", new FileBody(new File(chemin)));
httpPost.setEntity(builder.build());
httpClient.execute(httpPost, localContext);
}
catch (Exception e)
{
e.printStackTrace();
return -1;
}
return 0;
}
public void onPostExecute(Integer integer)
{
if(integer == 1)
Toast.makeText(getActivity(), "Good.", Toast.LENGTH_LONG).show();
else
Toast.makeText(getActivity(), "Bad.", Toast.LENGTH_LONG).show();
}
}
but when I try to run it a get the following error :
05-04 18:50:13.739: E/AndroidRuntime(2089): Caused by: java.lang.NoSuchFieldError: No static field INSTANCE of type Lorg/apache/http/message/BasicHeaderValueFormatter; in class Lorg/apache/http/message/BasicHeaderValueFormatter; or its superclasses (declaration of 'org.apache.http.message.BasicHeaderValueFormatter' appears in /system/framework/ext.jar)
at the line "httpPost.setEntity(builder.build());", the problem comes from "builder.build()". I've tried to add the httpClient.jar files to my project but it not works.
Can someone help me please ? Thanks !
Upvotes: 0
Views: 1163
Reputation: 1154
Sending images can be done using the HttpComponents libraries. Download the latest HttpClient 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;
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:
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("image" , new FileBody(new File (imagePath));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
} catch (IOException e) {
e.printStackTrace();
}
Don't use builder, directly pass the entity to the httpPost.setEntity()
Upvotes: 1