使用URL工具類調用webservice接口(soap)與http接口的實現方式


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class SoapTest {

public void testPost(String urlStr,String data) {
try {
//創建指定鏈接的url對象
URL url = new URL(urlStr);
//建立到url對象之間的鏈接
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//如果打算使用 URL 連接進行輸出,則將 DoOutput 標志設置為 true
con.setDoOutput(true);
//設置第一次請求的數據內容不被存儲
con.setRequestProperty("Pragma:", "no-cache");
//設置請求的數據內容不被存儲
con.setRequestProperty("Cache-Control", "no-cache");
//設置請求的字符集編碼格式,如果不指定,則默認采用16進制的字符集編碼格式
con.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
//構造向指定鏈接寫入數據的的輸出流
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
//獲取xml數據
String xmlInfo = getXmlInfo(data);
//向指定鏈接寫入數據
out.write(new String(xmlInfo));
out.flush();
out.close();
//將從服務端返回的數據讀取到內存中
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = "";
//構造一個空的StringBuffer對象,用於存儲內存中的數據
StringBuffer buf = new StringBuffer();
for (line = br.readLine(); line != null; line = br.readLine()) {
//由於服務端返回的數據的字符集編碼有可能不是utf-8,需要對返回的數據通過指定的字符集進行解碼
buf.append(new String(line.getBytes(),"UTF-8"));
}

//獲取服務端返回的HttpCode
  int httpCode = con.getResponseCode();
  System.out.println("HttpCode:"+httpCode+"  "+map.get("msgType")+"接口:"+buf.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//處理xml數據
public static String getXmlInfo(String data){
//對webservice接口進行加密(SHA-1加密)
SoapKey soapKey = new SoapKey();
String key=soapKey.getMessageDigest(data, "SHA-1");
//處理傳輸數據的"<"與">"字符
String str = new String(data.replace("<","&lt;")).replace(">","&gt;");
String xml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://service.ws.gpo.yy.com/\">"+"<soapenv:Header/>"
+"<soapenv:Body><ser:sendRecv4Supplier><!--Optional:--><sUser>zhuwei</sUser><!--Optional:--><sPwd>password</sPwd><!--Optional:--><sJgbm>GYSNB001</sJgbm><!--Optional:--><sVersion>1.0.0.0</sVersion><!--Optional:--><sXxlx>GS102</sXxlx><!--Optional:--><sSign>"+key+"</sSign><!--Optional:-->"
+"<xmlData>"+str+"</xmlData>"
+"</ser:sendRecv4Supplier></soapenv:Body></soapenv:Envelope>";
return xml;
}

public static void main(String[] args) throws UnsupportedEncodingException {
String url = "http://192.168.1.208:8090/gpodec/webservice/supplierService";
new SoapTest().testPost(url);

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM