OkHttp实现webService接口

引入依赖

        <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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值