Android multipartentity的用法

最近写一个程序,android手机端上传多个图片到asp.net服务器端,使用httpclient,在网上查到了使用multipartentity。上传测试时总是出现(500)Internal Server Error,最后查出原来是文件大小超出了服务器限制,在项目的web.config中添加:

<system.web>

    <HttpRuntime maxRequestLength="409600"  executionTimeout="60" />

</system.web>

对于简单的Post请求,使用UrlEncodedFormEntity,代码如下:

    public HttpPost makeHttpPost(String url,HashMap<String, String> map) throws Exception
    {
        HttpPost post = new HttpPost(url);
        List<NameValuePair> params = 
                new ArrayList<NameValuePair>();
            for(String key : map.keySet())
            {
                //封装请求参数
                params.add(new BasicNameValuePair(key 
                    , map.get(key)));
            }
            // 设置请求参数
            post.setEntity(new UrlEncodedFormEntity(
                params));
        return post;
    }

 

若需上传多文件,则要使用MultipartEntity,具体代码如下:

    public HttpPost sendPicture(String url,HashMap<String, String> map)
    {
        HttpPost post = new HttpPost(url);

        
        MultipartEntityBuilder m = MultipartEntityBuilder.create();
        m.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        for(int i = 0;i<picPaths.size();i++)
        { 
            File pic = new File(picPaths.get(i));
            //FileBody fb = new FileBody(pic);    
            //m.addPart("img"+i,new FileBody(pic));
            m.addBinaryBody("img"+i, pic);
        }
//        m.addPart("img", new FileBody(new File(picPaths.get(0))));//new ByteArrayBody
        for(String key : map.keySet())
        {
            Log.i("SENDTAG",(String)map.get(key));
            try {
//                post.getParams().setParameter(key, (String)map.get(key));
                m.addPart(key,new StringBody((String)map.get(key)));
                //m.addTextBody(key, (String)map.get(key));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        post.setEntity(m.build());
return post;
    }

 

代码已测试可用。

posted on 2014-06-26 23:19  一直在沉默  阅读(1557)  评论(0编辑  收藏  举报

导航