导航:首页 > 编程语言 > 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方法相关的资料

热点内容
nat地址访问外网服务器 浏览:966
怎样用java编译一个心形 浏览:934
如何使用python中的pygame 浏览:836
python实用小工具 浏览:24
怎么在安卓手机上去除马赛克 浏览:235
农行浓情通app怎么下载 浏览:533
怎么把原文件夹找回来 浏览:535
俄罗斯方块实现python思路 浏览:735
汉语拼音英语编译代码 浏览:501
程序员应具备的能力 浏览:606
手机石墨文档文件夹访问权限 浏览:656
客户端如何登陆域文件服务器 浏览:530
两位数的平方计算法 浏览:930
android图片分块 浏览:715
图形平移命令 浏览:962
聚类算法JAVA代码 浏览:407
网站图标素材压缩包 浏览:892
娱乐化app怎么做 浏览:638
加密货币行业前景如何 浏览:575
arm查询法的局限性和编译流程 浏览:81