在Java中执行get请求会导致HTTP响应代码:415

时间:2015-05-22 08:53:15

标签: java http

我尝试使用以下代码从网络服务中检索信息:

String kenteken = request.getParameter("InputKenteken");
        String uri = String.format("https://api.datamarket.azure.com/Data.ashx/opendata.rdw/VRTG.Open.Data/v1/KENT_VRTG_O_DAT('%s')", kenteken);

        URL url = new URL(uri);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestProperty("Content-Type","text/html");
        connection.setRequestMethod("GET");
        InputStream xml = connection.getInputStream();
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = null;
         try {
             db = dbf.newDocumentBuilder();
         } catch (ParserConfigurationException ex) {
             Logger.getLogger(CarServlet.class.getName()).log(Level.SEVERE, null, ex);
         }
         try {
             Document doc = db.parse(xml);
         } catch (SAXException ex) {
             Logger.getLogger(CarServlet.class.getName()).log(Level.SEVERE, null, ex);
         }
      }

当我从代码中调用URL时,我一直收到415响应代码,而URL在Chrome中工作正常。

enter image description here

这是我使用的网址:

https://api.datamarket.azure.com/Data.ashx/opendata.rdw/VRTG.Open.Data/v1/KENT_VRTG_O_DAT('jnzd27')

1 个答案:

答案 0 :(得分:3)

415 response code表示不支持所请求的媒体类型。如果您查看chrome的响应标头,您可以看到返回的内容类型是:

  Content-Type:application/atom+xml;type=entry;charset=utf-8

似乎接受这种确切的内容类型可以解决问题。因此,而不是:

connection.setRequestProperty("Content-Type","text/html");

使用:

connection.setRequestProperty("Accept","application/atom+xml");