引入依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.10.0</version>
</dependency>
打开自己webService的网页示例
Content-Type与代码中定义的 MediaType JSON对应
将请求的xml格式复制到RequestBody.create中
注意:需要将网页上所示的string留出来放置你所需要传递的参数
public static final MediaType JSON = MediaType.get("text/xml; charset=utf-8");
OkHttpClient client = new OkHttpClient();
public String postRecord(PassRecord passRecord) throws IOException {
List<PassRecord> passRecords = new ArrayList<>();
passRecords.add(passRecord);
PassRecordDTO passRecordDTO = new PassRecordDTO();
passRecordDTO.setMsg(passRecords);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
passRecordDTO.setTime(format.format(passRecord.getConfTime()));
String json = JSONObject.toJSONString(passRecordDTO);
String url = "http://10.135.21.181:8085/WebServiceTraceability.asmx?op=GetCoatPassStationInfo";
RequestBody body = RequestBody.create("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
" <soap:Body>\n" +
" <GetStopMgt_PSInfo xmlns=\"http://tempuri.org/\">\n" +
" <request>"+ json +"</request>\n" +
" </GetStopMgt_PSInfo>\n" +
" </soap:Body>\n" +
"</soap:Envelope>", JSON);
Request request = new Request.Builder()
.addHeader("Content-Type","text/xml; charset=utf-8")
.url(url)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
//url为webservice的url地址
//body内xml格式文件为soap响应示例需根据实际情况更改
DTO
根据自己实际需要或者webService接口返回来定义DTO
public class PassRecordDTO {
private List<PassRecord> msg;
private String time;
}