在Java中执行get请求会导致HTTP响应代码:415
我正在尝试使用以下代码从Web服务检索信息:在Java中执行get请求会导致HTTP响应代码:415,java,http,Java,Http,我正在尝试使用以下代码从Web服务检索信息: 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 UR
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中运行良好
这是我使用的URL:
表示不支持请求的媒体类型。如果查看chrome的响应标题,您可以看到返回的内容类型为:
Content-Type:application/atom+xml;type=entry;charset=utf-8
接受这种确切的内容类型似乎可以解决问题。因此,不是:
connection.setRequestProperty("Content-Type","text/html");
使用:
使用connection.setRequestProperty(“Accept”、“application/atom+xml”);解决了这个问题,谢谢!您用于解析响应的代码似乎不起作用。
connection.setRequestProperty("Accept","application/atom+xml");