java实现之测试第三方接口是否能正确连接

来源:互联网 发布:门诊流程优化 编辑:程序博客网 时间:2024/05/16 08:24
package com.hz.test;


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


public class Main {


public static void main(String[] args) {


if(true){
String aa=null;
System.out.println(aa);
return ;
}


String address = "http://spm01.gdpr.com/Webservice/NPMService1.asmx?wsdl";
testWsdlConnection(address);
}


public static int testWsdlConnection(String address) {

String WSDL = "http://127.0.0.1:8080/SMSService/webservices/SMSService";
String result = null;
try {
result = callWebService(WSDL);
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println(result);
int status = 404;
try {
URL urlObj = new URL(address);
HttpURLConnection oc = (HttpURLConnection) urlObj.openConnection();
oc.setUseCaches(false);
oc.setConnectTimeout(3000); // 设置超时时间
status = oc.getResponseCode();// 请求状态
if (200 == status) {
System.out.println("请求地址顺利连通。。GjcbdwxxUtil。" + address);
return status;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("请求地址不通。。GjcbdwxxUtil。" + address);
}
return status;
}


private static String actionBySOAP() {
StringBuilder sb = new StringBuilder();
sb.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas"
+ ".xmlsoap.org/soap/envelope/\" xmlns:sms=\"helloworld\">");
sb.append("<soapenv:Header/>");
sb.append("<soapenv:Body>");
sb.append("<sms:sendSMS>");
sb.append("<sms:in0>123</sms:in0>");
sb.append("</sms:sendSMS>");
sb.append("</soapenv:Body>");
sb.append("</soapenv:Envelope>");
return sb.toString();
}


private static String callWebService(String wsdl) throws Exception {
System.setProperty("sun.net.client.defaultConnectTimeout", "20000");
System.setProperty("sun.net.client.defaultReadTimeout", "20000");


// URL连接
URL url = new URL(wsdl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// conn.setRequestMethod("GET");
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Length",
String.valueOf(actionBySOAP().getBytes().length));
conn.setRequestProperty("Content-Type", "text/xml; charset=GBK");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(20000);
// 请求输入内容
OutputStream output = conn.getOutputStream();
output.write(actionBySOAP().getBytes());
output.flush();
output.close();
// 请求返回内容
InputStreamReader isr = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String str = null;
while ((str = br.readLine()) != null) {
sb.append(str + "\n");
}
br.close();
isr.close();
return sb.toString();
}


}
0 0