发送图片来自httppost

时间:2015-05-04 18:58:49

标签: android

我尝试使用httppost发送图像,这是我的代码:

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();
    }
}

但是当我尝试运行它时会出现以下错误:

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)

在“httpPost.setEntity(builder.build());”行,问题来自“builder.build()”。 我试图将httpClient.jar文件添加到我的项目中,但它不起作用。

是的,有人能帮帮我吗? 谢谢!

1 个答案:

答案 0 :(得分:1)

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()