版本4.3.5更新的代码
- 的HttpClient-4.3.5.jar
- 的HttpCore-4.3.2.jar
- httpmime-4.3.5.jar
由于MultipartEntity
已被弃用。请参阅下面的代码。
String responseBody = "failure";
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
String url = WWPApi.URL_USERS;
Map<String, String> map = new HashMap<String, String>();
map.put("user_id", String.valueOf(userId));
map.put("action", "update");
url = addQueryParams(map, url);
HttpPost post = new HttpPost(url);
post.addHeader("Accept", "application/json");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(MIME.UTF8_CHARSET);
if (career != null)
builder.addTextBody("career", career, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (gender != null)
builder.addTextBody("gender", gender, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (username != null)
builder.addTextBody("username", username, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (email != null)
builder.addTextBody("email", email, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (password != null)
builder.addTextBody("password", password, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (country != null)
builder.addTextBody("country", country, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (file != null)
builder.addBinaryBody("Filedata", file, ContentType.MULTIPART_FORM_DATA, file.getName());
post.setEntity(builder.build());
try {
responseBody = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");
// System.out.println("Response from Server ==> " + responseBody);
JSONObject object = new JSONObject(responseBody);
Boolean success = object.optBoolean("success");
String message = object.optString("error");
if (!success) {
responseBody = message;
} else {
responseBody = "success";
}
} catch (Exception e) {
e.printStackTrace();
} finally {
client.getConnectionManager().shutdown();
}
正如我前面提到的,我发送的图像尺寸很小。那么我需要使用MultiPartEntity来发送它们吗? – primpap 2010-05-30 01:03:05
我肯定会推荐这个。这样你可能可以使用Django的功能来接收图像并将其存储起来。另一种方法是将图像中的字节流编码为base64编码的字符串,并将其解码为服务器端。但在我看来,这太麻烦了,而不是要走的路。 – Piro 2010-05-30 01:16:57
从图库中选择的图像在缩放到50 * 50倾角后发送到服务器。所以我没有添加到列表值名称对的路径。所以只有你提到的第二种方法似乎是可能的。 – primpap 2010-05-30 07:11:26