我试图在java中复制以下unix cURL命令:
curl -X POST http://api.nigelsmall.com/xml-cypher -d @test / files / abba.xml
编辑:
更具体地说,我试图在java中复制以下cURL命令:
curl -X POST http://api.nigelsmall.com/xml-cypher -d“
<?xml version='1.0' encoding='UTF-8' ?><group><member></member></group>
”
到目前为止,我有以下代码:
String urlString = "http://api.nigelsmall.com/xml-cypher";
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "application/xml");
conn.setDoOutput(true);
conn.setRequestMethod("POST");
String data = "<?xml version='1.0' encoding='UTF-8' ?><group><member></member></group>";
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write(data);
out.flush();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
out.close();
rd.close();
}
catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
但java.io.IOException:Server返回HTTP响应代码:400为URL:http://api.nigelsmall.com/xml-cypher。任何人都可以找到问题所在吗?
我唯一能想到的是,我可能需要将XML放在一个文件中并将其作为请求发送。但我不知道该怎么做。任何人都可以帮我这个吗?提前谢谢。
答案 0 :(得分:1)
这不是你的错。 Web服务的文档缺少一个重要的细节:
如果发布JSON,您可以这样做。发布XML时,您必须提供XML,如果以HTML格式发布:application/x-www-form-urlencoded
。
在服务的source code中,您可以看到:
def _convert(method):
a = request.accept_mimetypes.best_match(["application/json", "text/html"])
if a == "application/json":
xml = request.get_data().decode("utf-8")
else:
xml = request.form["xml"] # <-- xml is a form field!!
# ...
我已经尝试使用DavidWebb,它只是HttpURLConnection
周围的一个小包装,并且有效:
public void testNigelsmall() throws Exception {
String payload = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" +
"<group id=\"abba\">\n" +
" <member id=\"agnetha\">\n" +
" <name>Agnetha Fältskog</name>\n" +
" <birth date=\"1950-04-05\" />\n" +
" </member>\n" +
" <member id=\"frida\">\n" +
" <name>Anni-Frid Lyngstad</name>\n" +
" <birth date=\"1945-11-15\" />\n" +
" </member>\n" +
" <song id=\"waterloo\" release_date=\"1974-03-04\">\n" +
" <name>Waterloo</name>\n" +
" <length min=\"2\" sec=\"42\" />\n" +
" </song>\n" +
"</group>";
Webb webb = Webb.create();
Response<String> response = webb
.post("http://api.nigelsmall.com/xml-cypher")
.param("xml", payload)
.asString();
assertEquals(200, response.getStatusCode());
assertNotNull(response.getBody());
assertTrue(response.getBody().startsWith("CREATE"));
assertTrue(response.getBody().contains("(abba)-[:member]->(frida)"));
}
输出:
CREATE
(abba),
(agnetha {name:"Agnetha F\u00e4ltskog",`birth date`:"1950-04-05"}),
(frida {name:"Anni-Frid Lyngstad",`birth date`:"1945-11-15"}),
(waterloo {`length sec`:42,`length min`:2,name:"Waterloo"}),
(abba)-[:member]->(agnetha),
(abba)-[:member]->(frida),
(abba)-[:song {release_date:"1974-03-04"}]->(waterloo)