以JSON请求发送图像 [英] Send Image in JSON request
本文介绍了以JSON请求发送图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在将JSON
与REST
api结合使用以使用Web服务.
I'm using JSON
with REST
api for using web service.
现在,我还需要在请求中发送图片.有可能吗?
Now I also need to send Images in request. Is it possible?
如果是,我需要在客户端/服务器端进行哪些更改.
If yes, what changes do I need to do on client/server side.
在我的Java代码中,我应该如何发送图像内容(我需要单独设置内容类型)吗?
And in my Java code, how should I send the image content (do I need to set a content type separately)?
推荐答案
做到这一点的方法是将其作为内容发送到HttpPost请求中,如下所示:
The way to do that would be to send it as content inside a HttpPost request as below
HttpClient client = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(url);
String body = getMessageBody();
try
{
postRequest.setEntity(new StringEntity(body, "UTF8"));
postRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
HttpResponse response = client.execute(postRequest);
return response;
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
} catch (ClientProtocolException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
对图像进行字符串编码的方法是执行以下操作.
The way you would string encode the image would be to do the following.
BufferedImage img = ImageIO.read(new File("filename.jpg"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", baos);
baos.flush();
Base64 base = new Base64(false);
String encodedImage = base.encodeToString(baos.toByteArray());
baos.close();
encodedImage = java.net.URLEncoder.encode(encodedImage, "ISO-8859-1");
祝你好运
这篇关于以JSON请求发送图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文