Java访问远程服务

    随着webService的崛起,我们开始中会越来越多的使用到访问远程webService服务。当然对于不同的webService框架一般都有自己的client包供使用,但是如果使用webService框架自己的client包,那么必然需要在自己的代码中引入它的包,如果同时调运了多个不同框架的webService,那么就需要同时引入多个不同的client包,这样做是很烦的。Java本生提供访问远程服务的包,在java.net.*下。接下来我们就用Java原生的package访问webService。

 

1、发送GET请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class   ReadByGet  implements   Runnable {
     public   void   run() {
         try   {
             URL url =  new   URL(
                     "http://fanyi.youdao.com/openapi.do?keyfrom=gusi123123&key=1075925116&type=data&doctype=json&version=1.1&q=hello" );//此处访问有道的webService服务,参数都在url中
             URLConnection connection = url.openConnection(); //得到一个连接对象
             InputStream is = connection.getInputStream();
             InputStreamReader isr =  new   InputStreamReader(is,  "UTF-8" );
             BufferedReader br =  new   BufferedReader(isr); //用于读取返回的数据流
 
             StringBuffer sb =  new   StringBuffer(); //用于接收返回的数据
             String line =  null ;
             while   ((line = br.readLine()) !=  null ) {
                 sb.append(line);
             }
             System.out.println(sb.toString());
             br.close(); //关闭各种连接
             isr.close();
             is.close();
         catch   (IOException e) {
             e.printStackTrace();
         }
     }
}

 

2、发送POST请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class   ReadByPost  implements   Runnable {
     public   void   run() {
         try   {
             URL url =  new   URL( "http://fanyi.youdao.com/openapi.do" );//此处通过post访问有道webService
             // URLConnection connection = url.openConnection();
             HttpURLConnection connection = (HttpURLConnection) url
                     .openConnection(); //得到一个http的连接对象
             connection.addRequestProperty( "encoding" "UTF-8" );
             connection.setRequestMethod( "POST" ); //设置请求方式
             connection.setDoInput( true ); //设置可写入
             connection.setDoOutput( true ); //设置可读取
 
             OutputStream os = connection.getOutputStream();
             OutputStreamWriter osw =  new   OutputStreamWriter(os,  "UTF-8" );
             BufferedWriter bw =  new   BufferedWriter(osw); //定义写入流对象
 
             bw.write( "keyfrom=gusi123123&key=1075925116&type=data&doctype=xml&version=1.1&q=hello" );
             bw.flush(); //通过写入流对象写入请求参数
 
             InputStream is = connection.getInputStream();
             InputStreamReader isr =  new   InputStreamReader(is,  "UTF-8" );
             BufferedReader br =  new   BufferedReader(isr); //定义读取流对象
 
             StringBuffer sb =  new   StringBuffer();
             String line =  null ;
             while   ((line = br.readLine()) !=  null ) {
                 sb.append(line);
             } //通过读取流读取返回数据
 
             //关闭各种连接对象
             br.close();
             isr.close();
             is.close();
             bw.close();
             osw.close();
             os.close();
 
             System.out.println(sb.toString());
         catch   (IOException e) {
             e.printStackTrace();
         }
     }
}

 

    通过上面也发现使用java原生的package访问webService比较麻烦,然后我们伟大的apache也给我们提供通用的访问webService的jar包,需要的jar包依赖是:(使用到的类在org.apache.http.*)

<dependency>

    <groupId>org.apache.httpcomponents</groupId>

    <artifactId>httpclient</artifactId>

    <version>4.3.6</version>

</dependency>

 

3、通过httpclient发送GET请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public   class   ReadByClientGet  implements   Runnable {
     HttpClient client = HttpClients.createDefault();
 
     public   void   run() {
         String uri =  "http://www.baidu.com" ;//访问百度
         HttpGet get =  new   HttpGet(uri); //得到请求对象
         try   {
             HttpResponse response = client.execute(get); //执行访问请求
             HttpEntity entity = response.getEntity(); //得到返回数据
             String result = EntityUtils.toString(entity,  "UTF-8" ); //将返回数据输出
             System.out.println(result);
         catch   (ClientProtocolException e) {
             e.printStackTrace();
         catch   (IOException e) {
             e.printStackTrace();
         }
     }
}

 

4、通过httpclient发送POST请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public   class   ReadByClientPost  implements   Runnable {
     HttpClient client = HttpClients.createDefault(); //创建一个client对象
     public   void   run() {
         try   {
             String uri =  "http://fanyi.youdao.com/openapi.do" ;//post访问有道webService
             HttpPost post =  new   HttpPost(uri); //得到post请求对象
             //构造请求参数,通过NameValuePair对象(类似于Map集合)
             List<NameValuePair> parameters =  new   ArrayList<NameValuePair>();
             parameters.add( new   BasicNameValuePair( "keyfrom" "gusi123123" ));
             parameters.add( new   BasicNameValuePair( "key" "1075925116" ));
             parameters.add( new   BasicNameValuePair( "type" "data" ));
             parameters.add( new   BasicNameValuePair( "doctype" "json" ));
             parameters.add( new   BasicNameValuePair( "version" "1.1" ));
             parameters.add( new   BasicNameValuePair( "q" "java" ));
             post.setEntity( new   UrlEncodedFormEntity(parameters, "UTF-8" ));
 
             HttpResponse response = client.execute(post); //执行post请求,并且接收返回数据
             HttpEntity entity = response.getEntity();
             String result = EntityUtils.toString(entity,  "UTF-8" );
             System.out.println(result); //输出返回数据
         catch   (ClientProtocolException e) {
             e.printStackTrace();
         catch   (IOException e) {
             e.printStackTrace();
         }
     }
}

    通过上面httpclient只是最简单的基本的访问webService服务。当然还有很多其他细节以及功能可以设计和处理。接下来通过测试方法测试上面的四种访问请求的结果:(输出结果不再粘贴)

1
2
3
4
5
6
7
8
public   class   Main {
     public   static   void   main(String[] args) {
         // new Thread(new ReadByGet()).start();
         // new Thread(new ReadByPost()).start();
         // new Thread(new ReadByClientGet()).start();
         //new Thread(new ReadByClientPost()).start();
     }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以使用URLConnection类或者Apache HttpClient库来读取远程服务器的文件列表。 1. 使用URLConnection类: 首先,创建一个URL对象,指定要访问远程服务器地址。然后,使用URL对象的openConnection()方法打开一个连接,并转换为HttpURLConnection对象。接着,设置HTTP请求的方法(GET、POST等)、超时时间等属性,并连接到远程服务器。通过getInputStream()方法获取远程服务器的响应数据流,并使用BufferedReader逐行读取文件列表。 以下是示例代码: ``` import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class RemoteFileReader { public static void main(String[] args) { try { URL url = new URL("https://example.com/filelist"); // 替换为实际的远程服务器地址 HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); // 设置连接超时时间为5秒 connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); // 输出远程服务器的文件列表 } reader.close(); connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ``` 2. 使用Apache HttpClient库: 首先,引入Apache HttpClient库的相关依赖。然后,创建一个HttpClient对象,并使用HttpGet请求指定的远程服务器地址。通过调用execute()方法发送请求并获取响应。使用EntityUtils类将响应的实体转换为字符串,并解析获取文件列表信息。 以下是示例代码: ``` import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class RemoteFileReader { public static void main(String[] args) { try { HttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("https://example.com/filelist"); // 替换为实际的远程服务器地址 HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); String filelist = EntityUtils.toString(entity); // 获取文件列表字符串 System.out.println(filelist); // 输出远程服务器的文件列表 httpClient.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 无论是使用URLConnection类还是Apache HttpClient库,需要替换示例代码中的远程服务器地址为实际的地址。在实际应用中,可能需要根据远程服务器的访问授权、协议、端口等设置相关参数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值