導航:首頁 > 編程語言 > java調用webservice方法

java調用webservice方法

發布時間:2023-11-09 04:53:09

1. java客戶端調用Webservice介面流程

給你看看以前寫的獲取電話號碼歸屬地的代碼的三種方法,然後你就懂了。

importjava.io.ByteArrayOutputStream;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.net.HttpURLConnection;
importjava.net.URL;

importorg.apache.commons.httpclient.HttpClient;
importorg.apache.commons.httpclient.HttpException;
importorg.apache.commons.httpclient.methods.PostMethod;

publicclassMobileCodeService{

publicvoidhttpGet(Stringmobile,StringuserID)throwsException
{
//http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode=string&userID=string
URLurl=newURL("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode="+mobile+"&userID="+userID);
HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");

if(conn.getResponseCode()==HttpURLConnection.HTTP_OK)//200
{
InputStreamis=conn.getInputStream();

=newByteArrayOutputStream();//

byte[]buf=newbyte[1024];
intlen=-1;
while((len=is.read(buf))!=-1)
{
//獲取結果
arrayOutputStream.write(buf,0,len);
}

System.out.println("Get方式獲取的數據是:"+arrayOutputStream.toString());
arrayOutputStream.close();
is.close();
}
}


publicvoidhttpPost(Stringmobile,StringuserID)throwsHttpException,IOException
{
//訪問路徑http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo
//HttpClient訪問

HttpClienthttpClient=newHttpClient();
PostMethodpm=newPostMethod("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo");

pm.setParameter("mobileCode",mobile);
pm.setParameter("userID",userID);

intcode=httpClient.executeMethod(pm);
System.out.println("狀態碼:"+code);

//獲取結果
Stringresult=pm.getResponseBodyAsString();
System.out.println("獲取到的數據是:"+result);
}

publicvoidSOAP()throwsException
{
HttpClientclient=newHttpClient();

PostMethodmethod=newPostMethod("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx");

//設置訪問方法的參數
method.setRequestBody(newFileInputStream("C:\soap.xml"));

method.setRequestHeader("Content-Type","text/xml;charset=utf-8");

intcode=client.executeMethod(method);
System.out.println("狀態碼:"+code);

//獲取結果
Stringresult=method.getResponseBodyAsString();
System.out.println("獲取到的數據是:"+result);
}

publicstaticvoidmain(String[]args)throwsException{
MobileCodeServicemcs=newMobileCodeService();
mcs.httpGet("18524012513","");
//mcs.httpPost("18524012513","");
//mcs.SOAP();
}
}

2. JAVA怎樣調用https類型的webservice

方法/步驟

一步按照Axis生成本地訪問客戶端,完成正常的webservice調用的開發,這里的細節我就不再描述,重點說明和http不同的地方-證書的生成和
使用。這里假設需要訪問的網址是https://www.abc.com
,那麼就需要生成網址的安全證書設置到系統屬性中,並且需要在調用代碼前。如下圖

第二步就是介紹怎樣生成證書,先寫一個InstallCert.java類放到自己電腦的D盤根目錄下,(注意這個類是沒有包名的)類中代碼如下:
/**
*
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
public class InstallCert {
public static void main(String[] args) throws Exception {
String host;
int port;
char[] passphrase;
if ((args.length == 1) || (args.length == 2)) {
String[] c = args[0].split(":");
host = c[0];
port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
String p = (args.length == 1) ? "changeit" : args[1];
passphrase = p.toCharArray();
} else {
System.out
.println("Usage: java InstallCert <host>[:port] [passphrase]");
return;
}

File file = new File("jssecacerts");
if (file.isFile() == false) {
char SEP = File.separatorChar;
File dir = new File(System.getProperty("java.home") + SEP + "lib"
+ SEP + "security");
file = new File(dir, "jssecacerts");
if (file.isFile() == false) {
file = new File(dir, "cacerts");
}
}
System.out.println("Loading KeyStore " + file + "...");
InputStream in = new FileInputStream(file);
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(in, passphrase);
in.close();

SSLContext context = SSLContext.getInstance("TLS");
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
X509TrustManager defaultTrustManager = (X509TrustManager) tmf
.getTrustManagers()[0];
SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
context.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory factory = context.getSocketFactory();

System.out
.println("Opening connection to " + host + ":" + port + "...");
SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
socket.setSoTimeout(10000);
try {
System.out.println("Starting SSL handshake...");
socket.startHandshake();
socket.close();
System.out.println();
System.out.println("No errors, certificate is already trusted");
} catch (SSLException e) {
System.out.println();
e.printStackTrace(System.out);
}

X509Certificate[] chain = tm.chain;
if (chain == null) {
System.out.println("Could not obtain server certificate chain");
return;
}

BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));

System.out.println();
System.out.println("Server sent " + chain.length + " certificate(s):");
System.out.println();
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
MessageDigest md5 = MessageDigest.getInstance("MD5");
for (int i = 0; i < chain.length; i++) {
X509Certificate cert = chain[i];
System.out.println(" " + (i + 1) + " Subject "
+ cert.getSubjectDN());
System.out.println(" Issuer " + cert.getIssuerDN());
sha1.update(cert.getEncoded());
System.out.println(" sha1 " + toHexString(sha1.digest()));
md5.update(cert.getEncoded());
System.out.println(" md5 " + toHexString(md5.digest()));
System.out.println();
}

System.out
.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
String line = reader.readLine().trim();
int k;
try {
k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
} catch (NumberFormatException e) {
System.out.println("KeyStore not changed");
return;
}

X509Certificate cert = chain[k];
String alias = host + "-" + (k + 1);
ks.setCertificateEntry(alias, cert);

OutputStream out = new FileOutputStream("jssecacerts");
ks.store(out, passphrase);
out.close();

System.out.println();
System.out.println(cert);
System.out.println();
System.out
.println("Added certificate to keystore 'jssecacerts' using alias '"
+ alias + "'");
}

private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();

private static String toHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 3);
for (int b : bytes) {
b &= 0xff;
sb.append(HEXDIGITS[b >> 4]);
sb.append(HEXDIGITS[b & 15]);
sb.append(' ');
}
return sb.toString();
}

private static class SavingTrustManager implements X509TrustManager {

private final X509TrustManager tm;
private X509Certificate[] chain;

SavingTrustManager(X509TrustManager tm) {
this.tm = tm;
}

public X509Certificate[] getAcceptedIssuers() {
throw new UnsupportedOperationException();
}

public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
throw new UnsupportedOperationException();
}

public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
this.chain = chain;
tm.checkServerTrusted(chain, authType);
}
}

}
將上面的InstallCert.java編譯成InstallCert.class文件放到自己電腦的D盤根目錄下。這是正常的情況下D盤根目錄下會有3個文件,

打開cmd進入到d盤開始執行生成證書命令,我這里不便於那我的網址測試我用支付寶的網址來測試的,輸入:java InstallCert

當出現了:Enter certificate to add to trusted keystore or 'q' to quit: [1]
這行代碼時,輸入1,回車。正常執行完後在D盤根目錄下就會出現證書「jssecacerts」文件,

得到證書後將證書拷貝到$JAVA_HOME/jre/lib/security目錄下,我這里是win7系統,在嘗試的過程中需要將證書重命名為:cacerts 放進去才會有用。(這個步驟在不同的環境和操作系統下有點不同,需要注意)

3. java語言使用post方式調用webService方式

WebService可以有Get、Post、Soap、Document四種方式調用,以下Java通過post方式調用WebService代碼:

importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.io.OutputStream;
importjava.io.OutputStreamWriter;
importjava.net.URL;
importjava.net.URLConnection;
importjava.net.URLEncoder;
importorg.apache.cxf.endpoint.Client;
importorg.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
/**
*功能描述:WebService調用
*
*/
publicclassClientTest{
/**
*功能描述:HTTP-POST
*
*/
publicStringpost(){
OutputStreamWriterout=null;
StringBuildersTotalString=newStringBuilder();
try{
URLurlTemp=newURL(
"http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getSupportCity");
URLConnectionconnection=urlTemp.openConnection();
connection.setDoOutput(true);
out=newOutputStreamWriter(connection.getOutputStream(),"UTF-8");
StringBuffersb=newStringBuffer();
sb.append("byProvinceName=福建");
out.write(sb.toString());
out.flush();
StringsCurrentLine;
sCurrentLine="";
InputStreaml_urlStream;
l_urlStream=connection.getInputStream();//請求
BufferedReaderl_reader=newBufferedReader(newInputStreamReader(
l_urlStream));
while((sCurrentLine=l_reader.readLine())!=null){
sTotalString.append(sCurrentLine);
}
}catch(Exceptione){
e.printStackTrace();
}finally{
if(null!=out){
try{
out.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
returnsTotalString.toString();
}
}

4. java程序怎麼調用webservice介面,實現發送簡訊功能

給你一個最簡單的方法:
第一、根據http://134.224.102.6:80/CompanySendSmInf/services/SmsInf?wsdl 拿到WSDL文件。
第二、根據Axis的jar包,把WSDL文件生成客服端java代碼。(可以把java文件打成jar文件,便於管理。怎麼生成java代碼,網路里都有說明我就不寫了。)
第三、在你工程里用AXIS的功能屬性,調用外部介面;給你一個格式模板:
MobileCodeWSLocator l=new MobileCodeWSLocator();//MobileCodeWSLocator是WSDL文件生成客服端java類;
MobileCodeWSSoap s=l.getMobileCodeWSSoap();();//MobileCodeWSSoap 是WSDL文件生成客服端java類

String m=s.getMobileCodeInfo("13811534742", "");
如果你用Axis生成的java類,格式和上面一樣;自己參考一下就懂了。

你上面明顯的連接異常,第三方服務明顯沒有開,WEBSERVICE可以設置戶名、密碼,像行所有的WEBSERVICE都設置,安全考慮吧。

5. 怎麼用Java通過wsdl地址調用WebService求代碼

6. java調用webservice錯誤:Could not send Message

看ping通要連webServiceip或者瀏覽器訪問址看能否現xml頁面報錯般網路通或埠問題。

7. java如何實現使用HTTP POST 的方式調用webservice

packagecom.weixin.util;

importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.io.StringWriter;
importjava.io.UnsupportedEncodingException;
importjava.util.ArrayList;
importjava.util.List;
importjava.util.Map;

importorg.apache.http.Header;
importorg.apache.http.HttpHost;
importorg.apache.http.HttpResponse;
importorg.apache.http.HttpStatus;
importorg.apache.http.HttpVersion;
importorg.apache.http.ParseException;
importorg.apache.http.client.ClientProtocolException;
importorg.apache.http.client.HttpClient;
importorg.apache.http.client.entity.UrlEncodedFormEntity;
importorg.apache.http.client.methods.HttpGet;
importorg.apache.http.client.methods.HttpPost;
importorg.apache.http.client.params.CookiePolicy;
importorg.apache.http.client.params.HttpClientParams;
importorg.apache.http.conn.params.ConnRoutePNames;
importorg.apache.http.impl.client.DefaultHttpClient;
importorg.apache.http.message.BasicNameValuePair;
importorg.apache.http.params.BasicHttpParams;
importorg.apache.http.params.HttpConnectionParams;
importorg.apache.http.params.HttpParams;
importorg.apache.http.params.HttpProtocolParams;
importorg.apache.http.protocol.HTTP;

//importbsh.ParseException;
importcom.google.gson.Gson;

/**
*TODO
*@Version1.0
*/
publicclassHttpClients{
/**UTF-8*/
privatestaticfinalStringUTF_8="UTF-8";
/**日誌記錄tag*/
privatestaticfinalStringTAG="HttpClients";

/**用戶host*/
privatestaticStringproxyHost="";
/**用戶埠*/
privatestaticintproxyPort=80;
/**是否使用用戶埠*/
privatestaticbooleanuseProxy=false;

/**連接超時*/
privatestaticfinalintTIMEOUT_CONNECTION=60000;
/**讀取超時*/
privatestaticfinalintTIMEOUT_SOCKET=60000;
/**重試3次*/
privatestaticfinalintRETRY_TIME=3;

/**
*@paramurl
*@paramrequestData
*@return
*/
publicStringdoHtmlPost(HttpClienthttpClient,HttpPosthttpPost)
{
StringresponseBody=null;

intstatusCode=-1;

try{

HttpResponsehttpResponse=httpClient.execute(httpPost);
HeaderlastHeader=httpResponse.getLastHeader("Set-Cookie");
if(null!=lastHeader)
{
httpPost.setHeader("cookie",lastHeader.getValue());
}
statusCode=httpResponse.getStatusLine().getStatusCode();
if(statusCode!=HttpStatus.SC_OK){
System.out.println("HTTP"+""+"HttpMethodfailed:"+httpResponse.getStatusLine());
}
InputStreamis=httpResponse.getEntity().getContent();
responseBody=getStreamAsString(is,HTTP.UTF_8);

}catch(Exceptione){
//發生網路異常
e.printStackTrace();
}finally{
// httpClient.getConnectionManager().shutdown();
// httpClient=null;
}

returnresponseBody;
}


/**
*
*發起網路請求
*
*@paramurl
*URL
*@paramrequestData
*requestData
*@returnINPUTSTREAM
*@throwsAppException
*/
publicstaticStringdoPost(Stringurl,StringrequestData)throwsException{
StringresponseBody=null;
HttpPosthttpPost=null;
HttpClienthttpClient=null;
intstatusCode=-1;
inttime=0;
do{
try{
httpPost=newHttpPost(url);
httpClient=getHttpClient();
//設置HTTPPOST請求參數必須用NameValuePair對象
List<BasicNameValuePair>params=newArrayList<BasicNameValuePair>();
params.add(newBasicNameValuePair("param",requestData));
UrlEncodedFormEntityentity=newUrlEncodedFormEntity(params,HTTP.UTF_8);
//設置HTTPPOST請求參數
httpPost.setEntity(entity);
HttpResponsehttpResponse=httpClient.execute(httpPost);
statusCode=httpResponse.getStatusLine().getStatusCode();
if(statusCode!=HttpStatus.SC_OK){
System.out.println("HTTP"+""+"HttpMethodfailed:"+httpResponse.getStatusLine());
}
InputStreamis=httpResponse.getEntity().getContent();
responseBody=getStreamAsString(is,HTTP.UTF_8);
break;
}catch(UnsupportedEncodingExceptione){
time++;
if(time<RETRY_TIME){
try{
Thread.sleep(1000);
}catch(InterruptedExceptione1){
}
continue;
}
//發生致命的異常,可能是協議不對或者返回的內容有問題
e.printStackTrace();

}catch(ClientProtocolExceptione){
time++;
if(time<RETRY_TIME){
try{
Thread.sleep(1000);
}catch(InterruptedExceptione1){
}
continue;
}
//發生致命的異常,可能是協議不對或者返回的內容有問題
e.printStackTrace();
}catch(IOExceptione){
time++;
if(time<RETRY_TIME){
try{
Thread.sleep(1000);
}catch(InterruptedExceptione1){
}
continue;
}
//發生網路異常
e.printStackTrace();
}catch(Exceptione){
time++;
if(time<RETRY_TIME){
try{
Thread.sleep(1000);
}catch(InterruptedExceptione1){
}
continue;
}
//發生網路異常
e.printStackTrace();
}finally{
httpClient.getConnectionManager().shutdown();
httpClient=null;
}
}while(time<RETRY_TIME);
returnresponseBody;
}

/**
*
*將InputStream轉化為String
*
*@paramstream
*inputstream
*@paramcharset
*字元集
*@return
*@throwsIOException
*/
(InputStreamstream,Stringcharset)throwsIOException{
try{
BufferedReaderreader=newBufferedReader(newInputStreamReader(stream,charset),8192);
StringWriterwriter=newStringWriter();

char[]chars=newchar[8192];
intcount=0;
while((count=reader.read(chars))>0){
writer.write(chars,0,count);
}

returnwriter.toString();
}finally{
if(stream!=null){
stream.close();
}
}
}

/**
*得到httpClient
*
*@return
*/
(){
finalHttpParamshttpParams=newBasicHttpParams();

if(useProxy){
HttpHostproxy=newHttpHost(proxyHost,proxyPort,"http");
httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
}

HttpConnectionParams.setConnectionTimeout(httpParams,TIMEOUT_CONNECTION);
HttpConnectionParams.setSoTimeout(httpParams,TIMEOUT_SOCKET);
HttpClientParams.setRedirecting(httpParams,true);
finalStringuserAgent="Mozilla/5.0(Windows;U;WindowsNT6.1;zh-CN;rv:1.9.2.14)Gecko/20110218Firefox/3.6.14";

HttpProtocolParams.setUserAgent(httpParams,userAgent);
HttpProtocolParams.setVersion(httpParams,HttpVersion.HTTP_1_1);
HttpClientParams.setCookiePolicy(httpParams,CookiePolicy.RFC_2109);

HttpProtocolParams.setUseExpectContinue(httpParams,false);
HttpClientclient=newDefaultHttpClient(httpParams);

returnclient;
}

/**
*
*得到httpClient
*
*@return
*/
(){
finalHttpParamshttpParams=newBasicHttpParams();

if(useProxy){
HttpHostproxy=newHttpHost(proxyHost,proxyPort,"http");
httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
}

HttpConnectionParams.setConnectionTimeout(httpParams,TIMEOUT_CONNECTION);
HttpConnectionParams.setSoTimeout(httpParams,TIMEOUT_SOCKET);
HttpClientParams.setRedirecting(httpParams,true);
finalStringuserAgent="Mozilla/5.0(Windows;U;WindowsNT6.1;zh-CN;rv:1.9.2.14)Gecko/20110218Firefox/3.6.14";

HttpProtocolParams.setUserAgent(httpParams,userAgent);
HttpProtocolParams.setVersion(httpParams,HttpVersion.HTTP_1_1);
HttpClientParams.setCookiePolicy(httpParams,CookiePolicy.BROWSER_COMPATIBILITY);
HttpProtocolParams.setUseExpectContinue(httpParams,false);
HttpClientclient=newDefaultHttpClient(httpParams);

returnclient;
}

/**
*列印返回內容
*@paramresponse
*@throwsParseException
*@throwsIOException
*/
publicstaticvoidshowResponse(Stringstr)throwsException{
Gsongson=newGson();
Map<String,Object>map=(Map<String,Object>)gson.fromJson(str,Object.class);
Stringvalue=(String)map.get("data");
//StringdecodeValue=Des3Request.decode(value);
//System.out.println(decodeValue);
//logger.debug(decodeValue);
}

/**
*
*發起網路請求
*
*@paramurl
*URL
*@paramrequestData
*requestData
*@returnINPUTSTREAM
*@throwsAppException
*/
publicstaticStringdoGet(Stringurl)throwsException{
StringresponseBody=null;
HttpGethttpGet=null;
HttpClienthttpClient=null;
intstatusCode=-1;
inttime=0;
do{
try{
httpGet=newHttpGet(url);
httpClient=getHttpClient();
HttpResponsehttpResponse=httpClient.execute(httpGet);
statusCode=httpResponse.getStatusLine().getStatusCode();
if(statusCode!=HttpStatus.SC_OK){
System.out.println("HTTP"+""+"HttpMethodfailed:"+httpResponse.getStatusLine());
}
InputStreamis=httpResponse.getEntity().getContent();
responseBody=getStreamAsString(is,HTTP.UTF_8);
break;
}catch(UnsupportedEncodingExceptione){
time++;
if(time<RETRY_TIME){
try{
Thread.sleep(1000);
}catch(InterruptedExceptione1){
}
continue;
}
//發生致命的異常,可能是協議不對或者返回的內容有問題
e.printStackTrace();

}catch(ClientProtocolExceptione){
time++;
if(time<RETRY_TIME){
try{
Thread.sleep(1000);
}catch(InterruptedExceptione1){
}
continue;
}
//發生致命的異常,可能是協議不對或者返回的內容有問題
e.printStackTrace();
}catch(IOExceptione){
time++;
if(time<RETRY_TIME){
try{
Thread.sleep(1000);
}catch(InterruptedExceptione1){
}
continue;
}
//發生網路異常
e.printStackTrace();
}catch(Exceptione){
time++;
if(time<RETRY_TIME){
try{
Thread.sleep(1000);
}catch(InterruptedExceptione1){
}
continue;
}
//發生網路異常
e.printStackTrace();
}finally{
httpClient.getConnectionManager().shutdown();
httpClient=null;
}
}while(time<RETRY_TIME);
returnresponseBody;
}
}

閱讀全文

與java調用webservice方法相關的資料

熱點內容
安卓界面更新時點擊卡頓如何解決 瀏覽:771
日本十大漫畫app哪個好用 瀏覽:876
做系統選擇哪個文件夾 瀏覽:283
如何登陸mc伺服器 瀏覽:799
華為無法定位伺服器地址 瀏覽:961
編譯原理第三版陳火旺課本圖片 瀏覽:566
cad用什麼解壓縮軟體 瀏覽:715
編譯的函數模版 瀏覽:359
加密貨幣利率改變 瀏覽:226
復雜網路案例python 瀏覽:296
死命令的意思 瀏覽:689
哪個app可以聽日語電台 瀏覽:103
谷輪壓縮機15hp 瀏覽:289
python任意整數冒泡降序 瀏覽:30
醫保卡的錢哪個app能看到 瀏覽:576
主伺服器崩潰如何進行域遷移 瀏覽:317
學安卓用什麼語言好 瀏覽:78
qt命令行 瀏覽:800
慕課app班級在哪裡 瀏覽:140
badusb編譯工具下載 瀏覽:191