通过HTTPPOST发送图像



我尝试发送带有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文件添加到我的项目中,但行不通。

有人可以帮我吗?谢谢!

可以使用httpcomponents库来发送图像。下载带有依赖项软件包的最新httpclient二进制文件,然后复制apache-mime4j-0.6.jar和httpmime-4.0.1.jar到您的项目中,并将它们添加到您的Java构建路径中。

您需要将以下导入添加到您的课程中。

import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;

现在,您可以创建一个多官方,将图像附加到您的发布请求。以下代码显示了如何执行此操作的示例:

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

不要使用构建器,直接将实体传递给httpPost.setEntity()

最新更新