使用HttpPost发送文件?

时间:2014-11-26 11:01:11

标签: android http-post multipartentity

我正在尝试使用HttpPost将图像发送到Web服务。问题是,当我尝试发送图像时返回一个未找到图像的错误,但是我在图库中选择了图像。

我该如何解决这个问题?

我在这里尝试

public Boolean insert(Usuario u, String fotoPath){
    HttpClient httpClient = new DefaultHttpClient();        
    HttpPost httppost = new HttpPost(urlPost.toString());

    try {
        File img = new File(fotoPath, ConvertStringToMD5.getMD5(u.getEmail().split("@")[0]));
        httppost.addHeader("Authorization", "Basic " + BasicAuthenticationRest.getBasicAuthentication());
        MultipartEntity me = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        me.addPart("nome", new StringBody(u.getNome()));
        me.addPart("email", new StringBody(u.getEmail()));
        me.addPart("senha", new StringBody(ConvertStringToMD5.getMD5(u.getSenha())));
        me.addPart("device_tipo", new StringBody("android"));
        me.addPart("device", new StringBody(AndroidReturnId.getAndroidId()));
        me.addPart("uploadedfile", new FileBody(img, "image/png"));         
        httppost.setEntity(me);

        HttpResponse response = httpClient.execute(httppost);
        HttpEntity entity = response.getEntity();
        if(entity != null){
                String js = EntityUtils.toString(entity);
                Log.i("JSON: ", js);
                JSONObject json = new JSONObject(js);
                if(json.getString("cod").equals("999")){
                    return true;
                }                
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
    return false;
}

logcat的

    11-26 09:53:01.945: D/ProgressBar(3673): setProgress = 0
11-26 09:53:01.945: D/ProgressBar(3673): setProgress = 0, fromUser = false
11-26 09:53:01.945: D/ProgressBar(3673): mProgress = 0mIndeterminate = false, mMin = 0, mMax = 10000
11-26 09:53:02.010: D/dalvikvm(3673): GC_FOR_ALLOC freed 166K, 18% free 17240K/20992K, paused 20ms, total 20ms
11-26 09:53:02.040: I/Path Foto:(3673): /storage/emulated/0/InstaSize.png
11-26 09:53:02.085: D/dalvikvm(3673): DexOpt: couldn't find static field Lorg/apache/http/message/BasicHeaderValueParser;.INSTANCE
11-26 09:53:02.085: W/dalvikvm(3673): VFY: unable to resolve static field 6632 (INSTANCE) in Lorg/apache/http/message/BasicHeaderValueParser;
11-26 09:53:02.085: D/dalvikvm(3673): VFY: replacing opcode 0x62 at 0x001b
11-26 09:53:02.090: D/dalvikvm(3673): DexOpt: couldn't find static field Lorg/apache/http/message/BasicHeaderValueFormatter;.INSTANCE
11-26 09:53:02.090: W/dalvikvm(3673): VFY: unable to resolve static field 6626 (INSTANCE) in Lorg/apache/http/message/BasicHeaderValueFormatter;
11-26 09:53:02.090: D/dalvikvm(3673): VFY: replacing opcode 0x62 at 0x0015
11-26 09:53:02.090: D/ProgressBar(3673): updateDrawableBounds: left = 0
11-26 09:53:02.090: D/ProgressBar(3673): updateDrawableBounds: top = 0
11-26 09:53:02.090: D/ProgressBar(3673): updateDrawableBounds: right = 96
11-26 09:53:02.090: D/ProgressBar(3673): updateDrawableBounds: bottom = 96
11-26 09:53:02.205: E/ViewRootImpl(3673): sendUserActionEvent() mView == null

1 个答案:

答案 0 :(得分:3)

您可以一次发送NameValuePairMultipartEntity ...

当您使用HttpPost时,您可以通过setEntity()方法发送参数..没有像appendEntity()这样的方法或者有些..所以你必须在一次设置参数..

您不能同时在NameValuePairMultipartEntity中发送参数..您必须选择其中一个..

因此,在您的代码中,您只会使用NameValuePair发送参数。您正在为图片创建MultipartEntity参数,但不是通过HTTPPost ...

发送的

试试这种方式..这可能对您有帮助..

 try {
    httppost.addHeader("Authorization", "Basic " + BasicAuthenticationRest.getBasicAuthentication());

    MultipartEntity me = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);         

    me.addPart("nome", new StringBody(getNome())); // to send string params 
    me.addPart("email", new StringBody(u.getEmail()));
    //other parameters

    //creating image/file parameter to send
    me.addPart("uploadedfile",new FileBody(new File(fotoPath))); // file parameter

    //setting entity to HTTPPost
    if(me!=null){
    //avoiding NullPointerException
    httppost.setEntity(new UrlEncodedFormEntity(me)); // sending MultipartEntity as entity
    }

    //getting response
    HttpResponse response = httpClient.execute(httppost);
    HttpEntity entity = response.getEntity();            
    if(entity != null){
            String js = EntityUtils.toString(entity);
            Log.i("JSON: ", js);
            JSONObject json = new JSONObject(js);
            if(json.getString("cod").equals("999")){
                return true;
            }                
    }
} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}