Sending a file with HttpPost?

…衆ロ難τιáo~ 提交于 2020-01-06 14:47:27

问题


I'm trying send an image to web service using HttpPost. The problem is when I try send image return an error that image does not found, but image exist I selected that in gallery.

How can I solve this ?

Here how I'm trying

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:


You can send either NameValuePair or MultipartEntity at a time...

When you are working with HttpPost, you can send parameters by setEntity() method.. there is no such methods like appendEntity() or somewhat.. so you have to set parameters at Once..

You can not send paramters in both NameValuePair and MultipartEntity at a time.. You have to choose one of them..

So in your code you are sending parameters with NameValuePair only. you are creating MultipartEntity parameter for image but you are not sending it with HTTPPost...

Try this way.. this may help you..

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


来源:https://stackoverflow.com/questions/27147409/sending-a-file-with-httppost

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!