導航:首頁 > 編程語言 > java客戶端調用webservice

java客戶端調用webservice

發布時間:2022-04-26 18:30:44

A. java 如何實現webservice 怎麼調用介面

一、利用jdkweb服務api實現,這里使用基於SOAPmessage的Web服務

①.首先建立一個WebservicesEndPoint:packageHello;
importjavax.jws.WebService;
importjavax.jws.WebMethod;
importjavax.xml.ws.Endpoint;
@WebService
publicclassHello{
@WebMethod
publicStringhello(Stringname){
return"Hello,"+name+" ";
}
publicstaticvoidmain(String[]args){
//createandpublishanendpoint
Hellohello=newHello();
Endpointendpoint=Endpoint.publish("


,hello);
}
}
②.使用apt編譯Hello.java(例:apt-d[存放編譯後的文件目錄]Hello.java),
會生成jaws目錄
③.使用javaHello.Hello運行,然後將瀏覽器指向


就會出現下列顯示
④.使用wsimport生成客戶端使用如下:
wsimport-p.-keep


這時,會在當前目錄中生成如下文件:
⑤.客戶端程序:
1classHelloClient{
2publicstaticvoidmain(Stringargs[]){
3HelloServiceservice=newHelloService();
4HellohelloProxy=service.getHelloPort();
5Stringhello=helloProxy.hello("你好");
6System.out.println(hello);
7}
8}

以上方法還稍顯繁瑣,還有更加簡單的方法


二、使用xfire,我這里使用的是myeclipse集成的xfire進行測試的利用xfire開發WebService,可以有三種方法:

1. 一種是從javabean中生成;

2.一種是從wsdl文件中生成;

3. 還有一種是自己建立webservice

步驟如下:

用myeclipse建立webservice工程,目錄結構如下:首先建立webservice介面,

代碼如下:

1packagecom.myeclipse.wsExample;
2//GeneratedbyMyEclipse
3
{
5
6publicStringexample(Stringmessage);
7
8}
接著實現這個借口:
1packagecom.myeclipse.wsExample;
2//GeneratedbyMyEclipse
3
{
5
6publicStringexample(Stringmessage){
7returnmessage;
8}
9
10}



修改service.xml文件,加入以下代碼:

1<service>
2<name>HelloWorldService</name>
3<serviceClass>
4com.myeclipse.wsExample.IHelloWorldService
5</serviceClass>
6<implementationClass>
7com.myeclipse.wsExample.HelloWorldServiceImpl
8</implementationClass>
9<style>wrapped</style>
10<use>literal</use>
11<scope>application</scope>
12</service>


把整個項目部署到tomcat伺服器中打開瀏覽器,輸入http://localhost:8989/HelloWorld/services/HelloWorldService?wsdl,可以看到如下:

然後再展開HelloWorldService後面的wsdl可以看到:

客戶端實現如下:

1packagecom.myeclipse.wsExample.client;
2
3importjava.net.MalformedURLException;
4importjava.net.URL;
5
6importorg.codehaus.xfire.XFireFactory;
7importorg.codehaus.xfire.client.Client;
8importorg.codehaus.xfire.client.XFireProxyFactory;
9importorg.codehaus.xfire.service.Service;
10importorg.codehaus.xfire.service.binding.ObjectServiceFactory;
11
12importcom.myeclipse.wsExample.IHelloWorldService;
13
14publicclassHelloWorldClient{
15publicstaticvoidmain(String[]args)throwsMalformedURLException,Exception{
16//TODOAuto-generatedmethodstub
17Services=newObjectServiceFactory().create(IHelloWorldService.class);
18XFireProxyFactoryxf=newXFireProxyFactory(XFireFactory.newInstance().getXFire());
19Stringurl="

20
21try
22{
23
24IHelloWorldServicehs=(IHelloWorldService)xf.create(s,url);
25Stringst=hs.example("zhangjin");
26System.out.print(st);
27}
28catch(Exceptione)
29{
30e.printStackTrace();
31}
32}
33
34}

有時候我們知道一個wsdl地址,比如想用java客戶端引用net做得webservice,使用myeclipse引用,但是卻出現無法通過驗證的錯誤,這時我們可以直接在類中引用,步驟如下:

1.publicstaticvoidmain(String[]args)throwsMalformedURLException,Exception{
2.//TODOAuto-generatedmethodstub



B. 如何在java web 裡面使用webservice技術

一、利用jdk web服務api實現,這里使用基於 SOAP message 的 Web 服務
1.首先建立一個Web services EndPoint:
package Hello;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.xml.ws.Endpoint;

@WebService
public class Hello {

@WebMethod
public String hello(String name) {
return "Hello, " + name + "\n";
}

public static void main(String[] args) {
// create and publish an endpoint
Hello hello = new Hello();
Endpoint endpoint = Endpoint.publish("http://localhost:8080/hello", hello);
}
}

2.使用 apt 編譯 Hello.java(例:apt -d [存放編譯後的文件目錄] Hello.java ) ,會生成 jaws目錄
3.使用java Hello.Hello運行,然後將瀏覽器指向http://localhost:8080/hello?wsdl就會出現下列顯示

4.使用wsimport 生成客戶端

使用如下:wsimport -p . -keep http://localhost:8080/hello?wsdl

這時,會在當前目錄中生成如下文件:

5.客戶端程序:

1class HelloClient{
2public static void main(String args[]) {
3 HelloService service = new HelloService();
4 Hello helloProxy = service.getHelloPort();
5 String hello = helloProxy.hello("你好");
6 System.out.println(hello);
7 }
8}
9

以上方法還稍顯繁瑣,還有更加簡單的方法

二、使用xfire,我這里使用的是myeclipse集成的xfire進行測試的
利用xfire開發WebService,可以有三種方法:
1一種是從javabean 中生成;
2 一種是從wsdl文件中生成;
3 還有一種是自己建立webservice
步驟如下:
用myeclipse建立webservice工程,目錄結構如下:

首先建立webservice介面,
代碼如下:

1package com.myeclipse.wsExample;
2//Generated by MyEclipse
3
4public interface IHelloWorldService {
5
6 public String example(String message);
7
8}
接著實現這個借口:
1package com.myeclipse.wsExample;
2//Generated by MyEclipse
3
4public class HelloWorldServiceImpl implements IHelloWorldService {
5
6 public String example(String message) {
7 return message;
8 }
9
10}
修改service.xml 文件,加入以下代碼:

1<service>
2 <name>HelloWorldService</name>
3 <serviceClass>
4 com.myeclipse.wsExample.IHelloWorldService
5 </serviceClass>
6 <implementationClass>
7 com.myeclipse.wsExample.HelloWorldServiceImpl
8 </implementationClass>
9 <style>wrapped</style>
10 <use>literal</use>
11 <scope>application</scope>
12 </service>
把整個項目部署到tomcat伺服器中 ,打開瀏覽器,輸入http://localhost:8989/HelloWorld/services/HelloWorldService?wsdl,可以看到如下:

然後再展開HelloWorldService後面的wsdl可以看到:

客戶端實現如下:
1package com.myeclipse.wsExample.client;
2
3import java.net.MalformedURLException;
4import java.net.URL;
5
6import org.codehaus.xfire.XFireFactory;
7import org.codehaus.xfire.client.Client;
8import org.codehaus.xfire.client.XFireProxyFactory;
9import org.codehaus.xfire.service.Service;
10import org.codehaus.xfire.service.binding.ObjectServiceFactory;
11
12import com.myeclipse.wsExample.IHelloWorldService;
13
14public class HelloWorldClient {
15public static void main(String[] args) throws MalformedURLException, Exception {
16// TODO Auto-generated method stub
17Service s=new ObjectServiceFactory().create(IHelloWorldService.class);
18XFireProxyFactory xf=new XFireProxyFactory(XFireFactory.newInstance().getXFire());
19String url="http://localhost:8989/HelloWorld/services/HelloWorldService";
20
21 try
22 {
23
24 IHelloWorldService hs=(IHelloWorldService) xf.create(s,url);
25 String st=hs.example("zhangjin");
26 System.out.print(st);
27 }
28 catch(Exception e)
29 {
30 e.printStackTrace();
31 }
32 }
33
34}
35
這里再說點題外話,有時候我們知道一個wsdl地址,比如想用java客戶端引用.net 做得webservice,使用myeclipse引用,但是卻出現無法通過驗證的錯誤,這時我們可以直接在類中引用,步驟如下:

1public static void main(String[] args) throws MalformedURLException, Exception {
2 // TODO Auto-generated method stub
3 Service s=new ObjectServiceFactory().create(IHelloWorldService.class);
4 XFireProxyFactory xf=new XFireProxyFactory(XFireFactory.newInstance().getXFire());
5
6
7//遠程調用.net開發的webservice
8Client c=new Client(new URL("http://www.webxml.com.cn/webservices/qqOnlineWebService.asmx?wsdl"));
9 Object[] o=c.invoke("qqCheckOnline", new String[]{"531086641","591284436"});
10
11//調用.net本機開發的webservice
12Client c1=new Client(new URL("http://localhost/zj/Service.asmx?wsdl"));
13Object[] o1=c1.invoke("HelloWorld",new String[]{});
14
15}

C. 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 放進去才會有用。(這個步驟在不同的環境和操作系統下有點不同,需要注意)

D. java客戶端調用webservice 超時問題

用多線程來處理類似問題
將調用這個WebService的程序放到一個獨立線程A中,再創建另一個線程B用來計時,線程A和線程B共享一個變數responseOK。

在線程A中調用WebService之前啟動線程B,成功返回後設定responseOK=true。
線程B啟動後計時,如果responseOK==true則停止計時,如果計時超過20秒,則終止線程A並返回錯誤信息。

似乎webService調用的時候如果服務端超時應該會有異常觸發的,截獲此異常即可。

E. 關於Webservice介面的Java客戶端調用

String endpoint="http://localhost:8080/xxx/services/userservice?wsdl";
String id = "11111";
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress(new URL(endpoint));
call.setOperationName("webservice方法名");
String res = (String) call.invoke(new Object[] {id});
看了你的描述覺得你把webservice想得太復雜化了,其實就是一個jar包和幾個類。
以上就是最簡單的webservice客戶端用法,和反射有點像。當然返回值不一定是String,返回的類型和格式要問服務提供方。
我用的是axis的,我不了解websphere什麼的,但是webservice就是那麼易用的東西。

F. java 怎樣調用本地webservice

WebService是基於Web的服務,WebService使用SOAP協議實現跨編程語言和跨操作系統平台,接收和響應外部系統的某種請求,從而實現遠程調用。WebService採用HTTP協議傳輸數據,採用XML格式封裝數據,SOAP協議=HTTP協議+XML數據格式。主要解決不了不同的系統或者調用分布部署的處理數據項目返回的介面。第一種,採用httpclient請求,這種跟經常用的HTTP請求一樣,結果可以是返回XML格式的字元串,比較容易對其進行解析,取得想要的數據。

G. 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();
}
}

H. java如何調用webservice介面

Java通過WSDL文件來調用webservice直接調用模式如下:

import java.util.Date;

import java.text.DateFormat;

import org.apache.axis.client.Call;

import org.apache.axis.client.Service;

import javax.xml.namespace.QName;

import java.lang.Integer;

import javax.xml.rpc.ParameterMode;

public class caClient {

public static void main(String[] args) {

try {

String endpoint = "http://localhost:8080/ca3/services/caSynrochnized?wsdl";

//直接引用遠程的wsdl文件

//以下都是套路

Service service = new Service();

Call call = (Call) service.createCall();

call.setTargetEndpointAddress(endpoint);

call.setOperationName("addUser");//WSDL裡面描述的介面名稱

call.addParameter("userName", org.apache.axis.encoding.XMLType.XSD_DATE,

javax.xml.rpc.ParameterMode.IN);//介面的參數

call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);//設置返回類型

String temp = "測試人員";

String result = (String)call.invoke(new Object[]{temp});

//給方法傳遞參數,並且調用方法

System.out.println("result is "+result);

}

catch (Exception e) {

System.err.println(e.toString());

}

}

}

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

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

J. Java客戶端調用Webservice介面求代碼

客戶端獲得自定義對象包路徑必須和伺服器端相同,當然在客戶端也可以不用建該對象,可以將客戶端的自定義對象打成jar包,然後在客戶端引用。

猜想用反射也可以實現改對象,但目前沒有寫相關例子。

<p>importjava.io.Serializable;</p><p>{
/**
*客戶端必須有與伺服器端相同的自定義對象
*/
=1L;
privateStringid;
privateStringname;
publicStringgetId(){
returnid;
}
publicvoidsetId(Stringid){
this.id=id;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}

}</p>
[java]viewplain
packageclient;

importpo.Hello;

{
/*
[java]viewplain
*該方法名必須和服務介面一致
[java]viewplain
*/
[java]viewplain
publicHelloexample();
[java]viewplain
<preclass="java"name="code">packageclient;

importjava.net.MalformedURLException;//importjava.net.URL;

//importorg.codehaus.xfire.client.Client;
importorg.codehaus.xfire.client.XFireProxyFactory;
importorg.codehaus.xfire.service.Service;
importorg.codehaus.xfire.service.binding.ObjectServiceFactory;

importpo.Hello;

publicclassServicesClient{
publicstaticvoidmain(String[]arg)throwsMalformedURLException,
Exception{
Stringxml="http://localhost:8080/web/services/HeloWebService";
=newObjectServiceFactory();
ServiceserviceModel=objectServiceFactory
.create(IClientHelloManager.class);
=newXFireProxyFactory();
IClientHelloManagerservice=(IClientHelloManager)xFireProxyFactory
.create(serviceModel,xml);
HellolHello=service.example();
System.out.println(lHello.getId());
System.out.println(lHello.getName());
//Clientclient=newClient(newURL(
//"http://localhost:8080/web/services/HeloWebService?wsdl"));
//Object[]rsult=client.invoke("example",newObject[]{"hello"});
//Hellohello=(Hello)rsult[0];
//System.out.println();
}
}</pre>
<pre></pre>
<pre></pre>
<pre></pre>
閱讀全文

與java客戶端調用webservice相關的資料

熱點內容
命令行沒有了怎麼回事 瀏覽:949
為什麼安卓軟體更新那麼快 瀏覽:838
學編程需要什麼數學基礎 瀏覽:229
沉浸式助眠asmr解壓 瀏覽:125
無證程序員是啥意思 瀏覽:231
成績中等的學生編程專業 瀏覽:132
基於滑動窗口計演算法 瀏覽:210
國家python發展 瀏覽:297
忘記加密密碼後該如何解開 瀏覽:712
python開發文件伺服器 瀏覽:349
重啟svn命令 瀏覽:598
python組合數據類型題庫解析 瀏覽:77
電腦解壓文件的安裝包 瀏覽:468
不培訓能幹程序員嗎 瀏覽:282
編譯器怎麼分享微信 瀏覽:798
四川加密防塵網廠 瀏覽:285
列印機怎麼連上伺服器 瀏覽:619
2k20解壓後不能進去 瀏覽:191
伺服器掉線後顯示什麼 瀏覽:207
python根據經緯度獲取國家 瀏覽:48