Answers:
我将假设您知道要上传的图像的路径和文件名。这个字符串添加你要NameValuePair
使用image
的键名。
可以使用HttpComponents库发送图像。下载具有依赖项软件包的最新HttpClient(当前为4.0.1)二进制文件,并将其复制apache-mime4j-0.6.jar
并复制httpmime-4.0.1.jar
到您的项目中,然后将其添加到Java构建路径中。
您将需要在类中添加以下导入。
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
现在,您可以创建一个MultipartEntity
将图像附加到POST请求。以下代码显示了如何执行此操作的示例:
public void post(String url, List<NameValuePair> nameValuePairs) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int index=0; index < nameValuePairs.size(); index++) {
if(nameValuePairs.get(index).getName().equalsIgnoreCase("image")) {
// If the key equals to "image", we use FileBody to transfer the data
entity.addPart(nameValuePairs.get(index).getName(), new FileBody(new File (nameValuePairs.get(index).getValue())));
} else {
// Normal string data
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
} catch (IOException e) {
e.printStackTrace();
}
}
希望这对您朝正确的方向有所帮助。
FileBody
所需的Mime Type。例如:new FileBody(new File (nameValuePairs.get(index).getValue()), "image/jpeg")
版本4.3.5更新的代码
由于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();
}
该循环J库可用于直接的用于此目的:
SyncHttpClient client = new SyncHttpClient();
RequestParams params = new RequestParams();
params.put("text", "some string");
params.put("image", new File(imagePath));
client.post("http://example.com", params, new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
// error handling
}
@Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
// success
}
});
我在尝试实现使用httpclient-4.3.5.jar,httpcore-4.3.2.jar,httpmime-4.3.5.jar将图像从Android客户端发布到servlet时费了很多力气。我总是遇到运行时错误。我发现基本上您不能在Android上使用这些jar,因为Google在Android中使用的是旧版HttpClient。此处的解释是http://hc.apache.org/httpcomponents-client-4.3.x/android-port.html。您需要从android http-client库获取httpclientandroidlib-1.2.1 jar。然后将您的导入从or.apache.http.client更改为ch.boye.httpclientandroidlib。希望这可以帮助。
我通常在处理json响应的线程中执行此操作:
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
如果需要对图像进行转换,则需要创建一个Drawable而不是Bitmap。