我想在设置Content-Type之后使用MultipartEntityBuilder将文件从Android上传到服务器,但也无法上传。
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
Log.d("Name", firstname+" "+lastname);
builder.addTextBody("firstName", firstname);
builder.addTextBody("lastName", lastname);
Log.d("ProfilePicturePath", picture);
if (picture.length()>0) {
builder.addPart("picture", new FileBody(new File(picture)));
}
Log.d("Boundary", boundary);
Log.d("URL", url);
String credentials = Base64.encodeToString((username+":"+password).getBytes(), Base64.NO_WRAP);
httpPost.setHeader("Authorization", "Basic "+credentials);
httpPost.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
Log.d("BasicAuthorization", credentials);
httpPost.setEntity(builder.build());
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
请仔细阅读我的代码,并向我提出一些解决方案。
答案 0 :(得分:0)
您可以使用FileBody
更新文件。这是一个小例子。
FileBody fileBody = new FileBody(file);
StringBody stringBody1 = new StringBody("Message 1", ContentType.MULTIPART_FORM_DATA);
StringBody stringBody2 = new StringBody("Message 2", ContentType.MULTIPART_FORM_DATA);
//
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("upfile", fileBody);
builder.addPart("text1", stringBody1);
builder.addPart("text2", stringBody2);
HttpEntity entity = builder.build();
//
post.setEntity(entity);
您可以使用getContentType
获取内容类型entity.getContentType()