【发布时间】:2018-03-02 00:39:46
【问题描述】:
我正在尝试使用 WebServices 将图像从 Android 应用程序发送到 Java 应用程序。
在服务器端,我有这段代码,使用 Postman 作为客户端可以正常工作:
@Path("/report")
public class ReportService {
@PUT
@Path("/put")
@Consumes(MediaType.APPLICATION_JSON)
public Report saveReport(String json){
return ReportDAO.saveReport(json);
}
另一方面,我的 android 应用程序正在尝试将图像上传到服务器:
try {
//Encode the image
String imagenPath = params[1];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap myBitmap = BitmapFactory.decodeFile(imagenPath);
myBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
//Create client,set url and entity
HttpClient httpClient = new DefaultHttpClient();
StringEntity entity = new StringEntity(encodedImage);
HttpPut httpPut = new HttpPut("http://10.0.2.2:8080/xxx/rest/report/put");
httpPut.setEntity(entity);
HttpResponse response = httpClient.execute(httpPut);
HttpEntity resp = response.getEntity();
}catch(Exception e){
e.printStackTrace();
}
}
我正在使用 Android Studio 的虚拟设备,它使用 GET 方法运行良好,但使用 POST/PUT 失败。
我没有得到任何异常,该方法甚至没有到达服务器。当我使用 EntityUtils 查看响应中的内容时,我得到一个空字符串。
在 Postman 上复制 URL 并将“http://10.0.2.2:8080”交换为“http://localhost:8080”正在到达服务器,但不是来自我的 Android 应用程序。
感谢您的帮助!
【问题讨论】: