最近接了个短信接口用的是webservice,查了下资料接上的 。记录一下
1.在url后面加上?wsdl获取到 targetNamespace
2.下载soapui对接口进行测试。并获取报文格式
3.最后就是根据报文组织查询 直接上工具类吧
package channel_ZhongXinJianTou;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import channel_ZhongZhouQH.Channel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* Http方式调用WebService
*
*/
public class Http {
public static Log log = LogFactory.getLog(Channel.class);
private static String urlWsdl = "http://ip:port/com/SmsInterface.cfc?wsdl";
private static String targetNamespace = "xxxxxx";//第一步获取到的数据
private static String OK = "<SendSmsReturn xsi:type=\"xsd:string\">0</SendSmsReturn>";
/**
* HttpURLConnection方式
* @param soap
*/
public static void httpURLConnection(String soap,String urlWsdl) {
HttpURLConnection connection = null;
try {
URL url = new URL(urlWsdl);
connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
connection.setRequestProperty("SOAPAction", targetNamespace + "toTraditionalChinese");//+ "toTraditionalChinese"
connection.connect();
setBytesToOutputStream(connection.getOutputStream(), soap.getBytes());
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
byte[] b = getBytesFromInputStream(connection.getInputStream());
String back = new String(b);
System.out.println("httpURLConnection返回soap:" + back);
//System.out.println("httpURLConnection结果:" + parseResult(back));
} else {
System.out.println("httpURLConnection返回状态码:" + connection.getResponseCode());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
connection.disconnect();
}
}
/**
* Commons-HttpClinet方式
* @param soap
*/
public static void commonsHttpClient(String soap) {
try {
org.apache.commons.httpclient.HttpClient httpclient = new org.apache.commons.httpclient.HttpClient();
org.apache.commons.httpclient.methods.PostMethod post = new org.apache.commons.httpclient.methods.PostMethod(urlWsdl);
post.addRequestHeader("Content-Type", "text/xml;charset=UTF-8");
post.addRequestHeader("SOAPAction", targetNamespace + "toTraditionalChinese");
org.apache.commons.httpclient.methods.RequestEntity entity = new org.apache.commons.httpclient.methods.InputStreamRequestEntity(new ByteArrayInputStream(soap.getBytes()));
post.setRequestEntity(entity);
int status = httpclient.executeMethod(post);
if (status == org.apache.commons.httpclient.HttpStatus.SC_OK) {
String back = post.getResponseBodyAsString();
System.out.println("Commons-HttpClinet返回soap:" + back);
//System.out.println("commons-HttpClinet返回结果:" + parseResult(back));
} else {
System.out.println("commons-HttpClinet返回状态码:" + status);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* HttpClient方式
* @param soap
*/
public static String httpClient(String soap,String urlWsdl) {
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(urlWsdl);
httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
httpPost.setHeader("SOAPAction", targetNamespace );//+ "toTraditionalChinese"
InputStreamEntity entity = new InputStreamEntity(new ByteArrayInputStream(soap.getBytes()));
httpPost.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_OK) {
HttpEntity responseEntity = response.getEntity();
String back = EntityUtils.toString(responseEntity);
log.info("httpClient返回soap:" + back);
if (back.contains(OK)){
return "1,0";
}else {
return "0,0";
}
//System.out.println("httpClient返回soap:" + back);
//System.out.println("httpClient返回结果:" + parseResult(back));
} else {
log.info("HttpClinet返回状态码:" + response.getStatusLine().getStatusCode());
//System.out.println("HttpClinet返回状态码:" + response.getStatusLine().getStatusCode());
return "0,0";
}
} catch (Exception e) {
log.info("异常"+e);
e.printStackTrace();
return "0,-100";
}
}
/**
* 从输入流获取数据
* @param in
* @return
* @throws IOException
*/
private static byte[] getBytesFromInputStream(InputStream in) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int len;
while ((len = in.read(b)) != -1) {
baos.write(b, 0, len);
}
byte[] bytes = baos.toByteArray();
return bytes;
}
/**
* 向输入流发送数据
* @param out
* @param bytes
* @throws IOException
*/
private static void setBytesToOutputStream(OutputStream out, byte[] bytes) throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
byte[] b = new byte[1024];
int len;
while ((len = bais.read(b)) != -1) {
out.write(b, 0, len);
}
out.flush();
}
/*private static String parseResult(String s) {
String result = "";
try {
Reader file = new StringReader(s);
SAXReader reader = new SAXReader();
Map<String, String> map = new HashMap<String, String>();
map.put("ns", "http://rpc.xml.coldfusion");
reader.getDocumentFactory().setXPathNamespaceURIs(map);
Document dc = reader.read(file);
result = dc.selectSingleNode("//ns:toTraditionalChineseResult").getText().trim();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}*/
public static void main(String[] args) {
StringBuffer xMLcontent = new StringBuffer("");
xMLcontent.append("<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:com=\"http://com\">");
xMLcontent.append(" <soapenv:Header/>");
xMLcontent.append(" <soapenv:Body>");
xMLcontent.append(" <com:SendSms soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">");
xMLcontent.append("<account xsi:type=\"xsd:string\">dx****</account>");
xMLcontent.append("<password xsi:type=\"xsd:string\">dx****</password>");
xMLcontent.append("<mobile xsi:type=\"xsd:string\">182****772</mobile>");
xMLcontent.append("<servicecode xsi:type=\"xsd:string\">6***3</servicecode>");
xMLcontent.append("<p1 xsi:type=\"xsd:string\">尊敬的客户,您的验证码为:440033</p1>");
xMLcontent.append("<sendtime xsi:type=\"xsd:string\"></sendtime>");
xMLcontent.append(" </com:SendSms>");
xMLcontent.append(" </soapenv:Body>");
xMLcontent.append("</soapenv:Envelope>");
//ttpURLConnection(xMLcontent.toString());
//httpURLConnection(soap12);
//commonsHttpClient(soap11);
//commonsHttpClient(soap12);
String s = httpClient(xMLcontent.toString(), urlWsdl);
System.out.println(s);
//httpClient(soap12);
}
}
jdk自己的api调用HttpURLConnection方式
public static void httpURLConnection(String soap) {
HttpURLConnection connection = null;
try {
URL url = new URL(urlWsdl);
connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
connection.setRequestProperty("SOAPAction", targetNamespace + "toTraditionalChinese");
connection.connect();
setBytesToOutputStream(connection.getOutputStream(), soap.getBytes());
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
byte[] b = getBytesFromInputStream(connection.getInputStream());
String back = new String(b);
System.out.println("httpURLConnection返回soap:" + back);
System.out.println("httpURLConnection结果:" + parseResult(back));
} else {
System.out.println("httpURLConnection返回状态码:" + connection.getResponseCode());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
connection.disconnect();
}
}
利用Srping的RestTemplate工具调用
public static void restTemplate(String soap) {
RestTemplate template = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("SOAPAction", targetNamespace + "toTraditionalChinese");
headers.add("Content-Type", "text/xml;charset=UTF-8");
org.springframework.http.HttpEntity<String> entity = new org.springframework.http.HttpEntity<String>(soap, headers);
ResponseEntity<String> response = template.postForEntity(urlWsdl, entity, String.class);
if (response.getStatusCode() == org.springframework.http.HttpStatus.OK) {
String back = template.postForEntity(urlWsdl, entity, String.class).getBody();
System.out.println("restTemplate返回soap:" + back);
System.out.println("restTemplate返回结果:" + parseResult(back));
} else {
System.out.println("restTemplate返回状态码:" + response.getStatusCode());
}
}
利用OkHttp工具调用
public static void okHttp(String soap) {
try {
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(soap, MediaType.get("text/xml;charset=UTF-8"));
Request request = new Request.Builder().url(urlWsdl).post(body)
.addHeader("SOAPAction", targetNamespace + "toTraditionalChinese").build();
Response response = client.newCall(request).execute();
String soapReturn = response.body().string();
System.out.println("okHttp返回soap:" + soapReturn);
System.out.println("okHttp结果:" + parseResult(soapReturn));
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.8.1</version>
</dependency>