Android上的HttpPut无法正常工作

问题描述 投票:0回答:2

我正在尝试使用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上复制网址并将“http://10.0.2.2:8080”交换为“http://localhost:8080”正在到达服务器,但不是来自我的Android应用程序。

感谢帮助!

android apache rest put
2个回答
1
投票

如你所说

在Postman上复制网址并将“http://10.0.2.2:8080”交换为“http://localhost:8080”正在到达服务器,但不是来自我的Android应用程序。

我假设您的网络服务与邮递员在同一台机器上。那是你的问题。

您需要创建一个服务器,将服务公开给您的本地网络端口。或者您需要一个公共IP托管服务。

您的代码很好,需要通过Internet或本地网络公开公开,并获得网络路径。只有这样它才会起作用。

您无法在不同的网络中找到您的PC,现在可以吗?这是客户端服务器通信和网络的ABC。


1
投票

你必须检查你的android studio虚拟设备和你的服务器是否在同一个子网中,以便你可以访问它。

您必须将网络从计算机暴露给虚拟设备才能使其正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.