为HttpURLConnection获取404

HJK*_*HJK 2 java android heroku httpurlconnection http-status-code-404

我在Heroku中部署了一个服务,生成pdf文件输出.当我点击浏览器中的URL时,我可以下载pdf文件(我没有提示保存(根据我的要求),它会自动保存到代码中的已定义路径).所以服务已经开始并且可用.但是当我使用HttpURLConnection访问它时,我收到404错误..任何人都可以帮我解决这个问题吗?

以下是我访问的链接:http: //quiet-savannah-7144.herokuapp.com/services/time/temp

以下是部署在Heroku服务器中的服务代码:

@jawax.ws.rs.core.Context
ServletContext context;

@GET
@path("/temp")
@Produces("application/pdf")
public Response getPdf() throws IOException{
  InputStream is = context.getResourceAsStream("/static/temp.pdf");
  ResponseBuilder res = Response.ok(is);
  res.header("Content-Disposition","attachment; filename=temp.pdf");
  return res.build();
}
Run Code Online (Sandbox Code Playgroud)

注意:我的文件位于webapp/static/temp.pdf

客户端代码如下:

 try {
         URL url = new URL("http://quiet-savannah-7144.herokuapp.com/sevices/time/temp");
         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
         conn.setDoOutput(true);
         conn.setRequestMethod("GET");
         conn.setRequestProperty("Content-Type", "application/json");
         int code = conn.getResponseCode();
         System.out.println("code>>"+code+"<<");
         if (conn.getResponseCode() == 200) {
            System.out.println("*************************done****************************");
            InputStream inputStream = conn.getInputStream();
            OutputStream output = new FileOutputStream("D:/copyOfTest.pdf");
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
               output.write(buffer, 0, bytesRead);
            }
            output.close();
         } else {
            Scanner scanner = new Scanner(conn.getErrorStream());
            while(scanner.hasNext())
            System.out.println(scanner.next());
            scanner.close();
         }
         conn.disconnect();
      } catch (MalformedURLException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
Run Code Online (Sandbox Code Playgroud)

我尝试使用pdf和x-pdf的内容类型,如下所示,没有任何工作

 conn.setRequestProperty("Content-Type", "application/pdf");
 conn.setRequestProperty("Content-Type", "application/x-pdf");
Run Code Online (Sandbox Code Playgroud)

当我在我的机器中的Tomcat服务器中本地部署服务时,事情是绝对正常的.我在过去的6个小时里一直在努力解决这个问题,但没有任何线索.其实我必须在android AsyncTask中获取它.如果我能够在java中完成它,那么我可以在android中实现相同的功能.有人可以帮我解决这个问题.

提前致谢

Sim*_*nni 10

我看到一些问题.

首先,如果你做GET,你不应该写conn.setDoOutput(true); 因为您没有从应用程序输出到服务器.

其次,Content-Type标头是你发送给服务器的内容类型,而不是相反的内容类型,所以既然你没有发送任何东西而只是做一个get,你就不应该设置它.

相反,也许,如果需要,您可以设置Accept标头.