java httpclient multipart/form-data 方式post

设置header后调用

服务端报错:org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

去掉请求头既可

/**
     * multipart/form-data
     * @param map
     * @param url
     * @param charset
     * @return
     */
    public String requestByPostParts(Map<String,Object> map, String url,String charset) {
        HttpClient httpClient = CustomHttpClient.GetHttpClient();//从连接池中获取
        HttpPost post = new HttpPost(url);
        //post.setHeader("Content-Type", "multipart/form-data");//去掉Header
        BufferedReader br = null;
        try
        {
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            if(map!=null) {
                Iterator iter = map.entrySet().iterator();
                while(iter.hasNext()){
                    Map.Entry entry = (Map.Entry) iter.next();
                    String key = (String) entry.getKey();
                    String value = (String) entry.getValue();
                    multipartEntityBuilder.addTextBody(key,value);
                }
            }
            HttpEntity httpEntity=multipartEntityBuilder.build();
            // 设置请求参数
            post.setEntity(httpEntity);
            // 发起交易
            HttpResponse resp = httpClient.execute(post);
            int ret = resp.getStatusLine().getStatusCode();
            // 响应分析
            HttpEntity entity = resp.getEntity();
            br = new BufferedReader(new InputStreamReader(entity.getContent(), charset));
            StringBuffer responseString = new StringBuffer();
            String result = br.readLine();
            while (result != null)
            {
                responseString.append(result);
                result = br.readLine();
            }
            return responseString.toString();
        } catch (Exception e)
        {
            log.error(e.getMessage(), e);
            return "";
        } finally
        {
            if (br != null)
            {
                try
                {
                    br.close();
                } catch (IOException e)
                {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

问题的原因:头部会自动加好,不要画足添蛇。

http://stackoverflow.com/questions/17415084/multipart-data-post-using-Python-requests-no-multipart-boundary-was-found

posted on 2017-08-02 15:30  13rj1115  阅读(4607)  评论(0编辑  收藏  举报

导航