我需要一个接一个地发送许多请求。我有一个代码:
,
我可以成功创建第一个请求。但是在第二个代码中,我有500个状态代码,而不是200个。这样的错误消息:
public void sendRestRequest(String xmlFile){
try{
String myRequest = generateStringFromResource(xmlFile);
given().auth().basic(prop.getProperty("restLogin"), prop.getProperty("restPassword"))
.contentType("application/xml")
.body(myRequest.getBytes(StandardCharsets.UTF_8))
.when()
.post(prop.getProperty("restURL"))
.then().
assertThat().statusCode(200).and().
assertThat().body("status", equalTo("UPLOADED"));
}
catch (Exception e){ LOG.error(String.valueOf(e)); }
}
public static String generateStringFromResource(String path) throws IOException {
return new String(Files.readAllBytes(Paths.get(path)));
}
可能有人有想法吗?我想应该是更紧密的连接或类似的东西。
答案 0 :(得分:0)
在服务器端,问题出在xml文件,但这很奇怪,因为如果我第一次发送该文件,则同一个文件没有问题。经过一番尝试,我决定使用效果很好的其他方法:
public void sendRestRequest(String xmlFile) throws IOException {
FileInputStream fis = new FileInputStream("configuration.properties");
prop.load(fis);
try {
URL url = new URL(prop.getProperty("restURL"));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/xml");
conn.setRequestProperty("Authorization", prop.getProperty("basic"));
String input = generateStringFromResource(xmlFile);
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
StringBuilder responseStrBuilder = new StringBuilder();
String output;
while ((output = br.readLine()) != null) {responseStrBuilder.append(output);}
conn.disconnect();
JSONObject result = new JSONObject(responseStrBuilder.toString());
Assert.assertEquals(result.getString("status"), "UPLOADED");
} catch (IOException e) {
LOG.error(String.valueOf(e));
}
}