我尝试使用RestAssured
将JSON发布到Rest服务,但会引发java.net.ConnectException
错误。
由于我的JSON消息很复杂,我已经在txt文件中提供了它。
public class PPJson {
public static void main(String[] args) throws IOException, JSONException {
BufferedReader tempreader = new BufferedReader(new FileReader("/Users/RestService/Jsonfileinput.txt"));
StringBuilder sbuilder = new StringBuilder();
String line = tempreader.readLine();
while (line != null) {
sbuilder.append(line);
line = tempreader.readLine();
}
tempreader.close();
//Initializing Rest API's URL
String APIUrl = "http://api.sample.com/api/v3/parcel/collect?apiKey={Value}";
//Initializing payload or API body
String APIBody = sbuilder.toString();
// Building request using requestSpecBuilder
RequestSpecBuilder builder = new RequestSpecBuilder().setBody(APIBody).setContentType("application/json; charset=UTF-8");
RequestSpecification requestSpec = builder.build();
//Making post request with authentication
Response response = given().authentication().preemptive().basic("","").spec(requestSpec).when().post(APIUrl);
JSONObject JSONResponseBody = new JSONObject(response.body().asString());
//Fetching the desired value of a parameter
String result = JSONResponseBody.getString("status");
System.out.println(result);
}
}
答案 0 :(得分:0)
@all,问题已修复,删除了对RequestSpecs的引用,这里是代码段
public class ParcelPointJson {
public static void main(String[] args) throws IOException, JSONException {
BufferedReader tempreader = new BufferedReader(new FileReader("/Users/srkrish/gitTrial/pim-automation/RestService/Jsonfileinput.txt"));
StringBuilder sbuilder = new StringBuilder();
String line = tempreader.readLine();
while (line != null) {
sbuilder.append(line);
line = tempreader.readLine();
}
tempreader.close();
//Initializing Rest API's URL
String APIUrl = "http://api.staging.wow.parcelpoint.com.au/api/v3/parcel/collect?apiKey=09BH1TXV";
//Initializing payload or API body
String APIBody = sbuilder.toString();
//Making post request with authentication
Response response = given().contentType("application/json; charset=UTF-8").body(APIBody).when().post(APIUrl);
JSONObject JSONResponseBody = new JSONObject(response.body().asString());
//Fetching the desired value of a parameter
String result = JSONResponseBody.getString("parcelId");
System.out.println(result);
//Assert.assertEquals(result, "200");
}
}