Java 请求webServce接口 不带参数

最近对接了个webService的接口取数据,从网上良莠不齐的代码中找到了个方法, 具体作者已经记不住是谁了,现在把代码贴出来,希望可以帮到大家,代码如下,简单粗暴

public String getWebService(){
        HttpURLConnection connection = null;
        OutputStream os = null;
        int responseCode = 0;
        StringBuilder sb = new StringBuilder();

        //第一步:创建服务地址,不是WSDL地址  
        URL url = null;
        try {
            url = new URL("");   //*****这里填写url地址
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  
        //第二步:打开一个通向服务地址的连接  
        try {
            connection = (HttpURLConnection) url.openConnection();
            //第三步:设置参数  
            //3.1发送方式设置:POST必须大写  
            connection.setRequestMethod("POST");
            //3.2设置数据格式:content-type  
            connection.setRequestProperty("content-type", "text/xml;charset=utf-8");  
            //3.3设置输入输出,因为默认新创建的connection没有读写权限,  
            connection.setDoInput(true);  
            connection.setDoOutput(true);  
            os = connection.getOutputStream();  
            //第五步:接收服务端响应,打印  
            responseCode = connection.getResponseCode(); 

            String temp = null; 
            if(200 == responseCode){//表示服务端响应成功  
                InputStream is = connection.getInputStream();  
                InputStreamReader isr = new InputStreamReader(is);  
                BufferedReader br = new BufferedReader(isr);  
                while(null != (temp = br.readLine())){  
                    sb.append(temp);  
                }  
                System.out.println(sb.toString());  
                is.close();  
                isr.close();  
                br.close();  
            }
            os.close(); 
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  

        return sb.toString();
    }
原文地址:https://www.cnblogs.com/kevinZhu/p/9241502.html