版本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