导航:首页 > 网络问题 > javaweb程序怎么去请求网络接口

javaweb程序怎么去请求网络接口

发布时间:2022-06-08 17:23:45

‘壹’ java调用 webservice 接口怎么调用

太简单了,这个跟Java访问url是一样的:

	/**
*程序中访问http数据接口
*@paramurlStrwebService地址地址
*/
(StringurlStr){
/**网络的url地址*/
URLurl=null;
/**http连接*/
HttpURLConnectionhttpConn=null;
/**//**输入流*/
BufferedReaderin=null;
StringBuffersb=newStringBuffer();
try{
url=newURL(urlStr);
in=newBufferedReader(newInputStreamReader(url.openStream(),"UTF-8"));
Stringstr=null;
while((str=in.readLine())!=null){
sb.append(str);
}
}catch(Exceptionex){
ex.printStackTrace();
}finally{
try{
if(in!=null){
in.close();
}
}catch(IOExceptionex){
ex.printStackTrace();
}
}
Stringresult=sb.toString();
System.out.println(result);
returnresult;
}

然后解析字符串就好了。是不是很简单

‘贰’ javaweb如何实现请求和响应

先来看一个流程图:


服务器处理请求的流程:

(1)服务器每次收到请求时,都会为这个请求开辟一个新的线程。

(2)服务器会把客户端的请求数据封装到request对象中,request就是请求数据的载体!

(3)服务器还会创建response对象,这个对象与客户端连接在一起,它可以用来向客户端发送响应。

由流程图可以看出,在JavaWeb的请求与响应中,最重要的两个参数为request以及response,这两参数在Servlet的service( )方法中。

1、response概念:

response是Servlet.service方法的一个参数,类型为javax.servlet.http.HttpServletResponse。在客户端发出每个请求时,服务器都会创建一个response对象,并传入给Servlet.service()方法。response对象是用来对客户端进行响应的,这说明在service()方法中使用response对象可以完成对客户端的响应工作。

response对象的功能分为以下四种:

(1)设置响应头信息

(2)发送状态码

(3)设置响应正文

(4)重定向

2、response响应正文

response是响应对象,向客户端输出响应正文(响应体)可以使用response的响应流,repsonse一共提供了两个响应流对象:

(1)PrintWriter out = response.getWriter():获取字符流;

(2)ServletOutputStream out = response.getOutputStream():获取字节流;

当然,如果响应正文内容为字符,那么使用response.getWriter(),如果响应内容是字节,例如下载时,那么可以使用response.getOutputStream()。

注意,在一个请求中,不能同时使用这两个流!也就是说,要么你使用repsonse.getWriter(),要么使用response.getOutputStream(),但不能同时使用这两个流。不然会抛出illegalStateException异常。

‘叁’ java怎么调用网上的webservice接口

Java通过WSDL文件来调用webservice:

注意,以下的代码并没有经过真正的测试,只是说明这些情况,不同版本的Axis相差很大,大家最好以apache网站上的例子为准,这里仅仅用于说明其基本用法。
1,直接AXIS调用远程的web service
这种方法比较适合那些高手,他们能直接看懂XML格式的WSDL文件,我自己是看不懂的,尤其我不是专门搞这行的,即使一段时间看懂,后来也就忘记了。直接调用模式如下:
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());
}
}
}
2,直接SOAP调用远程的webservice
这种模式我从来没有见过,也没有试过,但是网络上有人贴出来,我也转过来
import org.apache.soap.util.xml.*;
import org.apache.soap.*;
import org.apache.soap.rpc.*;

import java.io.*;
import java.net.*;
import java.util.Vector;

public class caService{
public static String getService(String user) {
URL url = null;
try {
url=new URL("http://192.168.0.100:8080/ca3/services/caSynrochnized");
} catch (MalformedURLException mue) {
return mue.getMessage();
}
// This is the main SOAP object
Call soapCall = new Call();
// Use SOAP encoding
soapCall.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
// This is the remote object we're asking for the price
soapCall.setTargetObjectURI("urn:xmethods-caSynrochnized");
// This is the name of the method on the above object
soapCall.setMethodName("getUser");
// We need to send the ISBN number as an input parameter to the method
Vector soapParams = new Vector();

// name, type, value, encoding style
Parameter isbnParam = new Parameter("userName", String.class, user, null);
soapParams.addElement(isbnParam);
soapCall.setParams(soapParams);
try {
// Invoke the remote method on the object
Response soapResponse = soapCall.invoke(url,"");
// Check to see if there is an error, return "N/A"
if (soapResponse.generatedFault()) {
Fault fault = soapResponse.getFault();
String f = fault.getFaultString();
return f;
} else {
// read result
Parameter soapResult = soapResponse.getReturnValue ();
// get a string from the result
return soapResult.getValue().toString();
}
} catch (SOAPException se) {
return se.getMessage();
}
}
}
3,使用wsdl2java把WSDL文件转成本地类,然后像本地类一样使用,即可。
这是像我这种懒人最喜欢的方式,仍然以前面的global weather report为例。
首先 java org.apache.axis.wsdl.WSDL2Java http://www.webservicex.net/globalweather.asmx.WSDL
原本的网址是http://www.webservicex.net/globalweather.asmx?WSDL,中间个各问号,但是Linux下面它不能解析,所以去掉问号,改为点号。
那么就会出现4个文件:
GlobalWeather.java GlobalWeatherLocator.java GlobalWeatherSoap.java GlobalWeatherSoapStub.java
其中GlobalWeatherSoap.java是我们最为关心的接口文件,如果你对RMI等SOAP实现的具体细节不感兴趣,那么你只需要看接口文件即可,在使用的时候,引入这个接口即可,就好像使用本地类一样。

‘肆’ 一个接口是javaweb项目的接口,ios怎么调用这个接口

在B系统写一个servlet(用ssh的话写个action,其实是一样的),在url上配置参数,B系统接受后进行逻辑处理,再把返回值print出去。

‘伍’ java调用webservice接口具体怎么调用

使用HttpClient
用到的jar文件:commons-httpclient-3.1.jar
方法:
预先定义好Soap请求数据,可以借助于XMLSpy Professional软件来做这一步生成。

String soapRequestData = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">" +
"<soap12:Body>" +
" <getCountryCityByIp xmlns=\"http://WebXml.com.cn/\">" +
" <theIpAddress>219.137.167.157</theIpAddress>" +
" </getCountryCityByIp>" +
" </soap12:Body>" +
"</soap12:Envelope>";

然后定义一个PostMethod,这时需要指定web服务的Url;

PostMethod postMethod = new PostMethod(“http://www.webxml.com.cn/WebServices/IpAddressSearchWebService.asmx”);

然后把Soap请求数据添加到PostMethod中

byte[] b = soapRequestData.getBytes("utf-8");
InputStream is = new ByteArrayInputStream(b,0,b.length);
RequestEntity re = new InputStreamRequestEntity(is,b.length,"application/soap+xml; charset=utf-8");
postMethod.setRequestEntity(re);

最后生成一个HttpClient对象,并发出postMethod请求

HttpClient httpClient = new HttpClient();
statusCode = httpClient.executeMethod(postMethod);
String soapRequestData = postMethod.getResponseBodyAsString();

soapRequestData就是调用web服务的Soap响应数据,是xml格式的,可以通过解析soapRequestData来获得调用web服务的返回值。

‘陆’ javaweb、jsp中调用外部的http接口

import java.net.*;
import java.io.*;

public class URLReader {
public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www..com/query.jsp?param1=value2¶m2=value2");
BufferedReader in = new BufferedReader(
new InputStreamReader(
yahoo.openStream()));

String inputLine;

while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);

in.close();
}
}

‘柒’ java 程序向其它程序提供接口如何完成

是指java 和其他语言的数据交互吗?
1:采用J2EE 的Servlet 完成特定功能,部署Tomcat后 其他语言中可通过Http请求访问
2:直接采用JSP ,和Servlet类似
3:采用Socket和其他程序通讯
4:采用中间件,比如 和Flex通讯 可以使用LCDS或者Blazeds 直接在Flex中调用Java端的方法..
5:采用WebService 使用web服务 与其他程序交互!

‘捌’ java如何调用接口方式

如果是已经有了URL的接口
URL url = new URL(接口);
创建链接对方接口对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

设置请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");

设置是否向httpUrlConnection输出,设置是否从httpUrlConnection读入

conn.setDoOutput(true);
conn.setDoInput(true);
最后断开链接,保证速度
conn.disconnect();
基本就这样用需要更多的就要自己看api了

‘玖’ 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



‘拾’ javaweb项目中怎么调用webservice的接口,并从客户端判断输入的数据,从接口反馈新数据~

您好,很高兴回答您的问题,
对于webservice 有2种风格:1:restful , 2:soap
对于第一种 是最直观的 webservice服务, 可以直接在浏览器上通过地址访问。
对于第二种 使用的是soap协议,在请求头上 需要添加soap头,
这二种 风格 都可以使用 httpconnection 进行调用, 只是 对于第二种会稍微麻烦一点。
另外 java 也有专门对于 webservice访问的包装, 如:cxf ,axis2 楼主可以对他们进行调查!

阅读全文

与javaweb程序怎么去请求网络接口相关的资料

热点内容
网络共享中心没有网卡 浏览:527
电脑无法检测到网络代理 浏览:1377
笔记本电脑一天会用多少流量 浏览:598
苹果电脑整机转移新机 浏览:1381
突然无法连接工作网络 浏览:1082
联通网络怎么设置才好 浏览:1230
小区网络电脑怎么连接路由器 浏览:1060
p1108打印机网络共享 浏览:1215
怎么调节台式电脑护眼 浏览:722
深圳天虹苹果电脑 浏览:957
网络总是异常断开 浏览:618
中级配置台式电脑 浏览:1019
中国网络安全的战士 浏览:639
同志网站在哪里 浏览:1422
版观看完整完结免费手机在线 浏览:1464
怎样切换默认数据网络设置 浏览:1114
肯德基无线网无法访问网络 浏览:1290
光纤猫怎么连接不上网络 浏览:1502
神武3手游网络连接 浏览:969
局网打印机网络共享 浏览:1005