【问题标题】:HttpPut on Android not workingAndroid上的HttpPut不起作用
【发布时间】: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 应用程序。

感谢您的帮助!

【问题讨论】:

    标签: android apache rest put


    【解决方案1】:

    如你所说

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

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

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

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

    您无法在其他网络中找到您的 PC,现在可以吗?这是客户端服务器通信和网络的基础知识。

    【讨论】:

    • 我在同一台机器上运行服务器和虚拟设备。我只是在使用真实设备之前测试这种通信。我不明白为什么我可以使用 10.0.2.2:8080/xxx/rest/user/get{name} 但不能使用 PUT/POST 方法。如果网络出现问题,get方法不应该失败吗? Ty 回复
    • 您应该检查防火墙的端口上的入站和出站流量,如果不存在,请添加防火墙规则。也可以通过邮递员检查。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-06-13
      • 1970-01-01
      • 2012-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      • 2015-03-04
      相关资源
      最近更新 更多