Java工作笔记-发送SOAP协议请求

这里搭建WebService采用JDKService那种最简单的方式,在此博文中不再说明。

以前说过,调用javaw的API封包是这样的:

这里模拟下。

客户端结构如下:

Java工作笔记-发送SOAP协议请求_第1张图片

源码如下:

Main2.java

package webservice.client;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;

public class Main2 {

    public static void main(String[] args) throws IOException {

        URL url = new URL("http://localhost:9998/weatherService?wsdl");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");

        //打开通信
        connection.setDoInput(true);
        connection.setDoOutput(true);

        //拼接符合协议需求的数据格式
        String info = buildXML("南京");
        connection.getOutputStream().write(info.getBytes());

        int responseCode = connection.getResponseCode();

        if(responseCode == 200){

            //正常
            InputStream inputStream = connection.getInputStream();
            Scanner sc = new Scanner(inputStream);
            while(sc.hasNext()){

                System.out.println(sc.nextLine());
            }
            sc.close();
        }
        else{

            System.out.println(responseCode);
        }
        System.out.println("over");
    }

    private static String buildXML(String cityName){

        String str = "";
        str += cityName;
        str += "";

        return str;
    }
}

 

你可能感兴趣的:(webservice,Java,java,webservice,http)