Java 在JSON请求中发送图像
我正在使用Java 在JSON请求中发送图像,java,android,json,rest,Java,Android,Json,Rest,我正在使用JSON和RESTapi来使用web服务 现在我还需要发送请求中的图像。可能吗 如果是,我需要在客户端/服务器端做什么更改 在我的Java代码中,我应该如何发送图像内容(是否需要单独设置内容类型)?您不应该发送图像本身,而应该发送可以从中下载图像的url 否则: 你的要求太大了 通常,您希望异步加载图像,这只有在内容与其他数据分离的情况下才能实现 您很可能无法使用自动JSON解析库,如GSON、Jackson或Adnroid SDK中集成的 对我有用的示例应用程序端代码。您可以在一个
JSON
和REST
api来使用web服务
现在我还需要发送请求中的图像。可能吗
如果是,我需要在客户端/服务器端做什么更改
在我的Java代码中,我应该如何发送图像内容(是否需要单独设置内容类型)?您不应该发送图像本身,而应该发送可以从中下载图像的url 否则:
- 你的要求太大了
- 通常,您希望异步加载图像,这只有在内容与其他数据分离的情况下才能实现
- 您很可能无法使用自动JSON解析库,如GSON、Jackson或Adnroid SDK中集成的
- 对我有用的示例应用程序端代码。您可以在一个值对中发送图像,在另一个值对中发送json:(此处“uploadedfile”标记将值对定义为签入post函数期间sd卡中图像文件的路径,其他标记将被视为文本数据)
列表值;值=新的ArrayList();
System.out.println(Constants.all_data.get(pos.getBookName());
添加(新的NameValuePair(“uploadedfile”,
常量.书本\图像\路径
+常量.all_data.get(pos.getImage());
添加(新的NameValuePair(“id”),常量.all_data.get(pos)
.getBookid()+“”);
添加(新的NameValuePair(“bookname”,Constants.all_数据
.get(pos.getBookName());
添加(新名称ValuePair(“价格”),常量.all_data.get(
pos.getPrice());
添加(新的NameValuePair(“WriterName”),常量.all_数据
.get(pos.getWriterName());
添加(新的NameValuePair(“publishername”,
常量.all_data.get(pos.getPublisherName());
职位(价值观);
//Post函数
public void post(final List<NameValuePair> nameValuePairs) {
// Setting progressDialog properties
progressDialog = ProgressDialog.show(CustomBookActivity.this, "",
"Syncing Book Data...");
mHandler = new Handler();
// Function to run after thread
mUpdateResults = new Runnable() {
public void run() {
progressDialog.dismiss();
// Something
}
};
new Thread() {
@Override
public void run() {
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("uploadedfile")) {
// If the key equals to "uploadedfile", 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);
HttpEntity result_entity = response.getEntity();
String htmlResponse = EntityUtils.toString(result_entity);
result = htmlResponse;
System.out.println("SYNC:::" + result);
// server = true;
} catch (IOException e) {
e.printStackTrace();
// server = false;
}
// dismiss the progress dialog
// Calling post function
mHandler.post(mUpdateResults);
}
}.start();
}
public void post(最终列表名称值对){
//设置progressDialog属性
progressDialog=progressDialog.show(CustomBookActivity.this,“,
“同步书本数据…”);
mHandler=新处理程序();
//要在线程之后运行的函数
mUpdateResults=new Runnable(){
公开募捐{
progressDialog.disclose();
//某物
}
};
新线程(){
@凌驾
公开募捐{
HttpClient HttpClient=新的DefaultHttpClient();
HttpContext localContext=新的BasicHttpContext();
HttpPost HttpPost=新的HttpPost(URL);
试一试{
多方实体=新多方实体(
HttpMultipartMode.BROWSER_兼容);
对于(int index=0;index
需要将Apache Mime4J、HTTPCore、HttpTime库JAR添加到项目中方法是将其作为HttpPost请求中的内容发送,如下所示
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();
}
对图像进行字符串编码的方法是执行以下操作
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");
祝你好运我在异步任务中使用了以下代码:
@Override
protected String doInBackground(String... str) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
String encodedImage = bitmapToString(mBitmap);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("data", encodedImage));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://192.168.0.107:8300/upload/upload");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String the_string_response = convertResponseToString(response);
return the_string_response;
} catch (Exception e) {
System.out.println("Error in http connection " + e.toString());
return "error";
}
}
public String bitmapToString(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String temp = null;
try {
System.gc();
temp = Base64.encodeToString(b, Base64.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
} catch (OutOfMemoryError e) {
baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
b = baos.toByteArray();
temp = Base64.encodeToString(b, Base64.DEFAULT);
Log.e("PictureDemo", "Out of memory error catched");
}
return temp;
}
private String convertResponseToString(HttpResponse response)
throws IllegalStateException, IOException {
String res = "";
StringBuffer buffer = new StringBuffer();
inputStream = response.getEntity().getContent();
int contentLength = (int) response.getEntity().getContentLength();
if (contentLength < 0) {
} else {
byte[] data = new byte[512];
int len = 0;
try {
while (-1 != (len = inputStream.read(data))) {
buffer.append(new String(data, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
res = buffer.toString();
}
return res;
}
@覆盖
受保护的字符串doInBackground(字符串…str){
ByteArrayOutputStream bas=新的ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.JPEG,100,baos);
字符串encodedImage=bitmapToString(mBitmap);
ArrayList nameValuePairs=新的ArrayList();
添加(新的BasicNameValuePair(“数据”,encodedImage));
试一试{
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(
"http://192.168.0.107:8300/upload/upload");
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=httpclient.execute(httppost);
字符串\u字符串\u响应=convertResponseToString(响应);
返回\u字符串\u响应;
}捕获(例外e){
System.out.println(“http连接中的错误”+e.toString());
返回“错误”;
}
}
公共字符串位图字符串(位图){
ByteArrayOutputStream bas=新的ByteArrayOutputStream();
位图.compress(位图.Comp
@Override
protected String doInBackground(String... str) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
String encodedImage = bitmapToString(mBitmap);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("data", encodedImage));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://192.168.0.107:8300/upload/upload");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String the_string_response = convertResponseToString(response);
return the_string_response;
} catch (Exception e) {
System.out.println("Error in http connection " + e.toString());
return "error";
}
}
public String bitmapToString(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String temp = null;
try {
System.gc();
temp = Base64.encodeToString(b, Base64.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
} catch (OutOfMemoryError e) {
baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
b = baos.toByteArray();
temp = Base64.encodeToString(b, Base64.DEFAULT);
Log.e("PictureDemo", "Out of memory error catched");
}
return temp;
}
private String convertResponseToString(HttpResponse response)
throws IllegalStateException, IOException {
String res = "";
StringBuffer buffer = new StringBuffer();
inputStream = response.getEntity().getContent();
int contentLength = (int) response.getEntity().getContentLength();
if (contentLength < 0) {
} else {
byte[] data = new byte[512];
int len = 0;
try {
while (-1 != (len = inputStream.read(data))) {
buffer.append(new String(data, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
res = buffer.toString();
}
return res;
}