/**
*
*/
/**
* @author admin
*
*/
package net.aykj.axcf.servlet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Hashtable;
import java.util.Iterator;
/**
*
* <p>Title: HttpClient.java</p>
* <p>Description:HttpURLConnection调用方式</p>
*/
public class HttpClient {
/**
* 禁止实例化
*/
private HttpClient() {
throw new IllegalStateException("工具类禁止实例化");
}
public static String executeMethod(Hashtable<?, ?> ht,String strUrl,String namespace) {
String RESULT="";
String SOAPAction = ht.get("Method").toString();
Iterator<String> itr = (Iterator<String>) ht.keySet().iterator();
String parameters = "";
for (int i = 0; i < ht.size(); i++) {
String key = (String)itr.next();
if(!"Method".equals(key)){
parameters = parameters + "<" + key + ">" + ht.get(key) + "</" + key + ">";
}
}
String soap = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+ "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
+ "<soap:Body>" + "<" + SOAPAction + " xmlns=\""+namespace+"\">" + parameters + " </" + SOAPAction
+ ">" + " </soap:Body>" + "</soap:Envelope>";
try {
URL url = new URL(strUrl);
URLConnection conn = url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(5000);
conn.setReadTimeout(8000);
conn.setRequestProperty("Content-Length", String.valueOf(soap.getBytes().length));
conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
conn.setRequestProperty("SOAPAction", namespace + SOAPAction);
OutputStream os = conn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");
osw.write(soap);
osw.flush();
osw.close();
InputStream is = conn.getInputStream();
RESULT = toString(is);
} catch (Exception e) {
e.printStackTrace();
}
return RESULT;
}
public static String toString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "/n");
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
/**
* @param args
*/
public static void main(String[] args) {
Hashtable<String, Object> ht = new Hashtable<String, Object>();
ht.put("UserId", "456");
ht.put("Time", "2017/12/28");
ht.put("T_Withdrawals", 1000);
ht.put("Method", "SetJ_Overview");
System.out.println(executeMethod(ht,"http://192.168.1.193:8081/WebService.asmx","http://tempuri.org/"));//http://tempuri.org/
}
}
java 调用.net web service
最新推荐文章于 2019-11-21 13:48:01 发布