【webservice】调试方法篇(二、java的http请求)

前面提过webservice调试工具,如果有兴趣动手写测试代码,那挺好的啊!

我也是这样想的,有想法不妨去尝试哦。那么,我的程序中主要用到HttpURLConnection类,先拼接符合soap协议的xml字符串信息,再与webservice服务端建立连接后,发送http请求,接收完返回信息后打印出来。流程上和SoapUI 调试工具的差不多的,下面提供测试程序的代码,大家可以参考一下。

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class Http {
	
	public String httpGet(String httpURL){
		String reqMsg = "" +
				"" +
				"username" +
				"userpw" +
				"" +
				"" +
				"" +
				"" +
				"" +
				"" +
					"32" +
					"321101" +
					"0" +
				"" +
				"" +				
				"11" +
				"" +
				"" +
				"";
		
		URL url = null; 
		HttpURLConnection httpURLConn= null;
        StringBuffer dataString = new StringBuffer("");
        String temp = new String();
		try{
            System.out.println(httpURL);
            url = new  URL(httpURL);
            httpURLConn= (HttpURLConnection)url.openConnection();
            httpURLConn.setDoOutput(true);
            httpURLConn.setRequestMethod("POST");
            httpURLConn.setConnectTimeout(300*1000);//300s超时
            httpURLConn.setRequestProperty("User-Agent","Apache-HttpClient/4.1.1 (java 1.5)");
            httpURLConn.setRequestProperty("Content-Type","application/soap+xml;charset=UTF-8;action=\"urn:SendXML\"");
            OutputStream out = httpURLConn.getOutputStream();
            out.write(reqMsg.toString().getBytes());
            httpURLConn.connect();
            InputStream in =httpURLConn.getInputStream();
            BufferedReader bd = new BufferedReader(new InputStreamReader(in));
            while((temp=bd.readLine())!=null)
            {
            	dataString.append(new String(temp.getBytes()));
            }  
            in.close();
            bd.close();
        }
        catch (Exception e){
            e.printStackTrace();
        } 
        finally{
            if(httpURLConn!=null){
                httpURLConn.disconnect();
            }
        }
        try{
	        System.out.println(new String(dataString.toString().getBytes("gbk"),"utf-8"));
        }catch(Exception e){
        	e.printStackTrace();
        }
        return dataString.toString();
	}

	public static void main(String[] arg){
		Http pm = new Http();
		pm.httpGet("http://132.xx.xxx.xx:8080/xxx//xxx?wsdl");
	
	}
}

有没有觉得拼接的这个xml,有点偏复杂?这个webservice服务端弄了soaphead 安全机制,没办法,客户端要求这样弄。往后再介绍一下这个带soaphead 安全机制的webservice服务端吧。

转载请说明出自whilejolly:http://blog.csdn.net/seedingly/article/details/39054609

你可能感兴趣的:(Java,逐步webservice)