restful接口客户端和服务端开发,HttpURLConnection,HttpClient,post ,get方式调用

Restful服务端及客户端调用实例

1.    新建web工程作为服务端à创建服务端代码

前情提示:

GET(SELECT):从服务器取出资源(一项或多项)。

POST(CREATE):在服务器新建一个资源。

PUT(UPDATE):在服务器更新资源(客户端提供改变后的完整资源)。

PATCH(UPDATE):在服务器更新资源(客户端提供改变的属性)。

DELETE(DELETE):从服务器删除资源。

2.服务端代码(每个方法前有注释,包括单参数,多参数,post,get方式的例子)

package com.eviac.blog.restws; 

import javax.ws.rs.Consumes;

import javax.ws.rs.DefaultValue;

import javax.ws.rs.FormParam;

import javax.ws.rs.GET; 

import javax.ws.rs.POST;

import javax.ws.rs.Path; 

import javax.ws.rs.PathParam; 

import javax.ws.rs.Produces;  

import javax.ws.rs.core.MediaType; 

 

import net.sf.json.JSONObject;

 

import com.alibaba.fastjson.JSONArray;

/**

 * 

 * @author pavithra

 * 

 */ 

 

// 这里@Path定义了类的层次路径。 

// 指定了资源类提供服务的URI路径。 

@Path("UserInfoService") 

public class UserInfo { 

    // @GET表示方法会处理HTTP GET请求 

    @GET 

    // 这里@Path定义了类的层次路径。指定了资源类提供服务的URI路径。 

   @Path("/name/{i}") 

    // @Produces定义了资源类方法会生成的媒体类型。 

   @Produces(MediaType.TEXT_XML) 

    // @PathParam向@Path定义的表达式注入URI参数值。 

    public String userName(@PathParam("i") 

    String i) { 

        String name = i; 

        return"<User>" + "<Name>" + name +"</Name>" + "</User>"; 

    } 

   

   

    @GET

    // 这里@Path定义了类的层次路径。指定了资源类提供服务的URI路径。 

   @Path("/userinfo/{id}") 

    // @Produces定义了资源类方法会生成的媒体类型

   //@Consumes(MediaType.APPLICATION_JSON) //传json

   @Produces(MediaType.APPLICATION_JSON) 

    // @PathParam向@Path定义的表达式注入URI参数值。 

    public StringuserJson(@PathParam("id") 

    String id) {

       //JSONObjectjobj=JSONObject.fromObject(id);

       //id=jobj.getString("id");

        return"{\"name\":\"hanzl\",\"age\":1,\"id\":"+"\""+id+"\"}"; 

    } 

   

  

    //多参数测试 

    @POST

    // 这里@Path定义了类的层次路径。指定了资源类提供服务的URI路径。 

   @Path("/user2info") 

    // @Produces定义了资源类方法会生成的媒体类型

   //@Consumes(MediaType.APPLICATION_JSON) //传json

    //多参数配置

    @Consumes({MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_FORM_URLENCODED})

   @Produces(MediaType.APPLICATION_JSON) //返回json

    // @PathParam向@Path定义的表达式注入URI参数值。 

    public Stringuser2Json(@FormParam("id")

    Stringid,@FormParam("name") String name) {

       System.out.println(id);

       System.out.println(name);

        return"{\"name\":"+"\""+name+"\""+",\"age\":1,\"id\":"+"\""+id+"\"}";

    } 

 

   

  //多参数测试   参数为json

    @POST

    // 这里@Path定义了类的层次路径。指定了资源类提供服务的URI路径。 

   @Path("/user3info") 

    // @Produces定义了资源类方法会生成的媒体类型

   //@Consumes(MediaType.APPLICATION_JSON) //传json

    //多参数配置

    @Consumes({MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_FORM_URLENCODED})

   @Produces(MediaType.APPLICATION_JSON) //返回json

    // @PathParam向@Path定义的表达式注入URI参数值。 

    public Stringuser3Json(@FormParam("id")

    String id) {

       System.out.println(id);

        return"{\"name\":\"hanzl\",\"age\":1,\"id\":"+"\""+id+"\"}";

    } 

 

    @GET 

    @Path("/age/{j}") 

   @Produces(MediaType.TEXT_XML) 

    public StringuserAge(@PathParam("j") 

    int j) { 

        int age = j; 

        return"<User>" + "<Age>" + age +"</Age>" + "</User>"; 

    } 

3.配置服务端web.xml(restful接口发布地址)在web.xml中加入如下配置

<servlet> 

        <servlet-name>Jersey RESTService</servlet-name> 

        <servlet-class> 

           com.sun.jersey.spi.container.servlet.ServletContainer 

        </servlet-class> 

        <init-param> 

            <param-name> 

               com.sun.jersey.config.property.packages 

            </param-name> 

           <param-value>com.eviac.blog.restws</param-value> 

        </init-param> 

       <load-on-startup>1</load-on-startup> 

    </servlet> 

    <servlet-mapping> 

        <servlet-name>Jersey RESTService</servlet-name> 

       <url-pattern>/rest/*</url-pattern> 

</servlet-mapping>

4.编写客户端代码

4.1新建java工程

来进行服务端的第一次调用:

packagecom.eviac.blog.restclient; 

 

import javax.ws.rs.core.MediaType; 

 

importcom.sun.jersey.api.client.Client; 

importcom.sun.jersey.api.client.ClientResponse; 

importcom.sun.jersey.api.client.WebResource; 

importcom.sun.jersey.api.client.config.ClientConfig; 

importcom.sun.jersey.api.client.config.DefaultClientConfig; 

 

/**

 * 

 * @author pavithra

 * 

 */ 

publicclass UserInfoClient { 

 

    public static final String BASE_URI ="http://localhost:8080/RestflService"; 

    public static final String PATH_NAME ="/UserInfoService/name/"; 

    public static final String PATH_AGE ="/UserInfoService/age/"; 

 

    public static void main(String[] args){ 

 

        String name ="Pavithra"; 

        int age = 25; 

 

        ClientConfig config = newDefaultClientConfig(); 

        Client client =Client.create(config); 

        WebResource resource =client.resource(BASE_URI); 

 

        WebResource nameResource =resource.path("rest").path(PATH_NAME + name); 

        System.out.println("ClientResponse \n" 

                +getClientResponse(nameResource)); 

        System.out.println("Response\n" + getResponse(nameResource) + "\n\n"); 

 

        WebResource ageResource =resource.path("rest").path(PATH_AGE + age); 

        System.out.println("Client Response\n" 

                +getClientResponse(ageResource)); 

        System.out.println("Response\n" + getResponse(ageResource)); 

    } 

 

    /**

     * 返回客户端请求。 例如: GET

     *http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra

     * 返回请求结果状态“200OK”。

     * 

     * @param service

     * @return

     */ 

    private static StringgetClientResponse(WebResource resource) { 

        returnresource.accept(MediaType.TEXT_XML).get(ClientResponse.class) 

                .toString(); 

    } 

 

    /**

     * 返回请求结果XML 例如:<User><Name>Pavithra</Name></User>

     * 

     * @param service

     * @return

     */ 

    private static StringgetResponse(WebResource resource) { 

        returnresource.accept(MediaType.TEXT_XML).get(String.class); 

    } 

}

调用结果:

 

4.2get方式还可以直接从浏览器直接调用

浏览器调用:

以上这些都是单纯的get方式提交的数据可使用

5.客户端调用我这有两种方式HttpURLConnection, HttpClient两种

5.1HttpURLConnection调用restful接口

代码如下:

package com.eviac.blog.restclient;

/****

 * 测试get请求方式,请求数据为单个参数,返回结果为json

 *get方法提交

 * 返回数据json

 */

import java.io.BufferedInputStream;

import java.io.BufferedReader;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

public class JavaNetURLRESTFulClient {

        

         //post方式

          public static String postDownloadJson(Stringpath,String post){

                 URL url = null;

//接口的地址

                 path="http://localhost:8080/RestflService/rest/UserInfoService/userinfo";

//请求的参数

                post="id=\"{\"id\":\"11\"}\"";  

                 try {

                     url = new URL(path);

                     HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();

                     httpURLConnection.setRequestMethod("POST");//提交模式

                     // conn.setConnectTimeout(10000);//连接超时 单位毫秒

                     // conn.setReadTimeout(2000);//读取超时 单位毫秒

                     // 发送POST请求必须设置如下两行

                    httpURLConnection.setDoOutput(true);

                     httpURLConnection.setDoInput(true);

                    //httpURLConnection.setRequestProperty("Content-Type","application/json; charset=utf-8");

                     // 获取URLConnection对象对应的输出流

                     PrintWriter printWriter = newPrintWriter(httpURLConnection.getOutputStream());

                     // 发送请求参数

                     printWriter.write(post);//post的参数xx=xx&yy=yy

                     // flush输出流的缓冲

                     printWriter.flush();

                     //开始获取数据

                     BufferedInputStream bis = newBufferedInputStream(httpURLConnection.getInputStream());

                     ByteArrayOutputStream bos = newByteArrayOutputStream();

                     int len;

                     byte[] arr = new byte[1024];

                     while((len=bis.read(arr))!= -1){

                         bos.write(arr,0,len);

                         bos.flush();

                     }

                     bos.close();

                     returnbos.toString("utf-8");

                 } catch (Exception e) {

                     e.printStackTrace();

                 }

                 return null;

             }

      public static void main(String[] args) {

                try {

                         String id="123";

                         String targetURL ="http://localhost:8080/RestflService/rest/UserInfoService/userinfo/";

                         targetURL+=id;

                     URL restServiceURL = newURL(targetURL);

                     HttpURLConnectionhttpConnection = (HttpURLConnection) restServiceURL.openConnection();

                    httpConnection.setRequestMethod("GET");

                     //返回xml

                     //httpConnection.setRequestProperty("Content-Type","text/plain; charset=utf-8");

                     //返回json

                    httpConnection.setRequestProperty("Accept","application/json");

                     if(httpConnection.getResponseCode() != 200) {

                            throw newRuntimeException("HTTP GET Request Failed with Error code : "

                                          +httpConnection.getResponseCode());

                     }

                     BufferedReaderresponseBuffer = new BufferedReader(new InputStreamReader(

                           (httpConnection.getInputStream())));

                     String output;

                    System.out.println("Output from Server:  \n");

                     while ((output =responseBuffer.readLine()) != null) {

                           System.out.println(output);

                     }

                     //解析json

                    httpConnection.disconnect();

                } catch (MalformedURLExceptione) {

                     e.printStackTrace();

                } catch (IOException e) {

                     e.printStackTrace();

                }

              }

      

               // postDownloadJson(null,null);

      

}

5.2HttpClient调用restful接口(post & get方式)

代码如下:

package com.eviac.blog.restclient;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

importorg.apache.commons.httpclient.HttpClient;

importorg.apache.commons.httpclient.HttpException;

importorg.apache.commons.httpclient.NameValuePair;

importorg.apache.commons.httpclient.methods.GetMethod;

importorg.apache.commons.httpclient.methods.PostMethod;

public class RestClient {

   public static void main(String[] args) {

       String urlpost ="http://localhost:8080/RestflService/rest/UserInfoService/user3info";

       String urlget ="http://localhost:8080/RestflService/rest/UserInfoService/name/1";

       HttpClient client = new HttpClient();

//POST方法

       GetMethod getmethod=new GetMethod(urlget);

       PostMethod method = new PostMethod(urlpost);

       NameValuePair[] data = {

                newNameValuePair("id","{\"id\":\"11\"}")};

       method.setRequestBody(data);

       try {

           int statusCode = client.executeMethod(method);

           if (statusCode == 200) {

              

                   

                    // String strJson =method.getResponseBodyAsString();

               // System.out.println("post方法="+strJson);

                BufferedReader reader = new BufferedReader(newInputStreamReader(method.getResponseBodyAsStream())); 

                StringBuffer stringBuffer = newStringBuffer(); 

                String str = ""; 

                while((str =reader.readLine())!=null){ 

                    stringBuffer.append(str); 

                } 

                String ts =stringBuffer.toString(); 

                System.out.println("post方法="+ts);

           }

       } catch (HttpException e) {

           e.printStackTrace();

       } catch (IOException e) {

           e.printStackTrace();

       }

       

       

     //执行get方法

       try {

           int statusCode = client.executeMethod(getmethod);

           if (statusCode == 200) {

                String strJson =getmethod.getResponseBodyAsString();

                System.out.println("get方法="+strJson);

               

                //System.out.println(map.get("user").getUsername());

           }

       } catch (HttpException e) {

           e.printStackTrace();

       } catch (IOException e) {

           e.printStackTrace();

       }

    }

   

}

5.3HttpURLConnection调用restful接口(post,多参数)

服务端方法配置:

//多参数测试 

   @POST

   //这里@Path定义了类的层次路径。指定了资源类提供服务的URI路径。 

   @Path("/user2info"

   // @Produces定义了资源类方法会生成的媒体类型

   //@Consumes(MediaType.APPLICATION_JSON) //json

   //多参数配置

   @Consumes({MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_FORM_URLENCODED})

   @Produces(MediaType.APPLICATION_JSON//返回json

   // @PathParam@Path定义的表达式注入URI参数值。 

   publicString user2Json(@FormParam("id")

   String id,@FormParam("name") Stringname) {

     System.out.println(id);

     System.out.println(name);

        return"{\"name\":"+"\""+name+"\""+",\"age\":1,\"id\":"+"\""+id+"\"}";

 

客户端调用:代码

package com.eviac.blog.restclient;

importjava.io.BufferedInputStream;

importjava.io.BufferedReader;

importjava.io.ByteArrayOutputStream;

importjava.io.IOException;

importjava.io.InputStreamReader;

importjava.io.PrintWriter;

importjava.net.HttpURLConnection;

importjava.net.MalformedURLException;

importjava.net.URL;

/**

 *

 * @author Hanlong

 *  多参数配置

 *  请求数据为为多个参数

 *  返回结果是Json

 *  放在body体里

 *  Post方法提交

 */

public classTest2paras {

 

  //post方式

   publicstatic String postDownloadJson(String path,String post){

         URL url = null;

         path="http://localhost:8080/RestflService/rest/UserInfoService/user2info";

         post="{\"id\":\"11\"}\"";

         String post1="id=1&name=hanzl";

         try {

             url = new URL(path);

             HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();

             httpURLConnection.setRequestMethod("POST");// 提交模式

             // conn.setConnectTimeout(10000);//连接超时 单位毫秒

             // conn.setReadTimeout(2000);//读取超时 单位毫秒

             // 发送POST请求必须设置如下两行

             httpURLConnection.setDoOutput(true);

             httpURLConnection.setDoInput(true);

             //httpURLConnection.setRequestProperty("Content-Type","application/json; charset=utf-8");

             // 获取URLConnection对象对应的输出流

             PrintWriter printWriter = newPrintWriter(httpURLConnection.getOutputStream());

             // 发送请求参数

             printWriter.write(post1);//post的参数 xx=xx&yy=yy

             // flush输出流的缓冲

             printWriter.flush();

             //开始获取数据

             BufferedInputStream bis = newBufferedInputStream(httpURLConnection.getInputStream());

             ByteArrayOutputStream bos = new ByteArrayOutputStream();

             int len;

             byte[] arr = new byte[1024];

             while((len=bis.read(arr))!= -1){

                 bos.write(arr,0,len);

                 bos.flush();

             }

             bos.close();

             return bos.toString("utf-8");

         } catch (Exception e) {

             e.printStackTrace();

         }

         return null;

      }

       public static void main(String[] args) {

 

      System.out.println(postDownloadJson(null,null));

       }

}

5.4HttpURLConnection调用restful接口(post,参数为json,返回参数为json)

服务端

//多参数测试  参数为json

   @POST

   //这里@Path定义了类的层次路径。指定了资源类提供服务的URI路径。 

   @Path("/user3info"

   // @Produces定义了资源类方法会生成的媒体类型

   //@Consumes(MediaType.APPLICATION_JSON) //json

   //多参数配置

   @Consumes({MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_FORM_URLENCODED})

   @Produces(MediaType.APPLICATION_JSON//返回json

   // @PathParam@Path定义的表达式注入URI参数值。 

   publicString user3Json(@FormParam("id")

   String id) {

     System.out.println(id);

        return"{\"name\":\"hanzl\",\"age\":1,\"id\":"+"\""+id+"\"}";

客户端代码

packagecom.eviac.blog.restclient;

importjava.io.BufferedInputStream;

importjava.io.BufferedReader;

importjava.io.ByteArrayOutputStream;

importjava.io.IOException;

importjava.io.InputStreamReader;

importjava.io.PrintWriter;

import java.net.HttpURLConnection;

importjava.net.MalformedURLException;

importjava.net.URL;

/**

 *

 * @author Hanlong

 *  多参数配置

 *  请求数据json

 *  返回结果是Json

 *  Post方法提交

 */

public classTestJsonparams {

     

      //post方式

       public static String postDownloadJson(Stringpath,String post){

             URL url = null;

             path="http://localhost:8080/RestflService/rest/UserInfoService/user3info";

             post="id={\"id\":\"11\"}\"";

             String post1=post;

             try {

                 url = new URL(path);

                 HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();

                 httpURLConnection.setRequestMethod("POST");// 提交模式

                 // conn.setConnectTimeout(10000);//连接超时 单位毫秒

                 // conn.setReadTimeout(2000);//读取超时 单位毫秒

                 // 发送POST请求必须设置如下两行

                 httpURLConnection.setDoOutput(true);

                 httpURLConnection.setDoInput(true);

                 //httpURLConnection.setRequestProperty("Content-Type","application/json; charset=utf-8");

                 // 获取URLConnection对象对应的输出流

                 PrintWriter printWriter = newPrintWriter(httpURLConnection.getOutputStream());

                 // 发送请求参数

                 printWriter.write(post1);//post的参数 xx=xx&yy=yy

                 // flush输出流的缓冲

                 printWriter.flush();

                 //开始获取数据

                 BufferedInputStream bis = newBufferedInputStream(httpURLConnection.getInputStream());

                 ByteArrayOutputStream bos = new ByteArrayOutputStream();

                 int len;

                 byte[] arr = new byte[1024];

                 while((len=bis.read(arr))!= -1){

                      bos.write(arr,0,len);

                      bos.flush();

                 }

                 bos.close();

                 return bos.toString("utf-8");

             } catch (Exception e) {

                 e.printStackTrace();

             }

             return null;

         }

       public static void main(String[] args) {

              

      

            System.out.println(postDownloadJson(null,null));

       }

}

 

6.项目完整包(附件带jar包)

https://download.csdn.net/download/hanzl1/10490670https://download.csdn.net/download/hanzl1/10490670

https://wenku.baidu.com/view/7a0cc78b846a561252d380eb6294dd88d0d23ddc

猜你喜欢

转载自blog.csdn.net/hanzl1/article/details/78627001