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

你可能感兴趣的:(httpclient,webservice,get,post)