HttpClient4上传图片


URI location = new URI(request.getLocationUri());
            HttpRequestBase req = null;
            String responseBody = "";

            req = new HttpPost(location);
            MultipartEntity reqEntity = new MultipartEntity();
            for (Map.Entry<String, byte[]> file : uploadFile.entrySet()) {
                reqEntity.addPart(file.getKey(),
                        new ByteArrayBody(file.getValue(), "re-signup.PNG"));
            }
            for (Map.Entry<String, Object> param : parameters.entrySet()) {
                reqEntity.addPart(param.getKey(), new StringBody((String) param.getValue()));
            }
            ((HttpPost) req).setEntity(reqEntity);
            // TODO 千万不要加这个,加了就拉稀了
//            req.setHeader(OAuth.HeaderType.CONTENT_TYPE, OAuth.ContentType.UPLOAD_FILE);

            HttpResponse response = client.execute(req);
            Header contentTypeHeader = null;
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseBody = EntityUtils.toString(entity, CommonParameters.UTF8);
                contentTypeHeader = entity.getContentType();
            }
            String contentType = null;
            if (contentTypeHeader != null) {
                contentType = contentTypeHeader.toString();
            }

注意:千万不要加req.setHeader,根据接口需要参数类型不同,可构造不同的ContentBody;

中文乱码问题:

StringBody stringBody = new StringBody((String) param.getValue(),
                        Charset.forName(CommonParameters.UTF8));
                reqEntity.addPart(param.getKey(), stringBody);

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM