Restful接口调用方法超详细总结

Restful接口调用方法超详细总结

由于在实际项目中碰到的restful服务,参数都以json为准。这里我获取的接口和传入的参数都是json字符串类型。发布restful服务可参照文章http://www.cnblogs.com/jave1ove/p/7277861.html,以下接口调用基于此服务。

基于发布的Restful服务,下面总结几种常用的调用方法。

(1)Jersey API

package com.restful.client;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.restful.entity.PersonEntity;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

import javax.ws.rs.core.MediaType;

/**

  • Created by XuHui on 2017/8/7.
    */
    public class JerseyClient {
    private static String REST_API = “http://localhost:8080/jerseyDemo/rest/JerseyService”;
    public static void main(String[] args) throws Exception {
    getRandomResource();
    addResource();
    getAllResource();
    }

    public static void getRandomResource() {
    Client client = Client.create();
    WebResource webResource = client.resource(REST_API + “/getRandomResource”);
    ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).accept(“application/json”).get(ClientResponse.class);
    String str = response.getEntity(String.class);
    System.out.print("getRandomResource result is : " + str + “\n”);
    }

    public static void addResource() throws JsonProcessingException {
    Client client = Client.create();
    WebResource webResource = client.resource(REST_API + “/addResource/person”);
    ObjectMapper mapper = new ObjectMapper();
    PersonEntity entity = new PersonEntity(“NO2”, “Joker”, “http://”);
    ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, mapper.writeValueAsString(entity));
    System.out.print("addResource result is : " + response.getEntity(String.class) + “\n”);
    }

    public static void getAllResource() {
    Client client = Client.create();
    WebResource webResource = client.resource(REST_API + “/getAllResource”);
    ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).accept(“application/json”).get(ClientResponse.class);
    String str = response.getEntity(String.class);
    System.out.print("getAllResource result is : " + str + “\n”);
    }
    }

结果:

getRandomResource result is : {"id":"NO1","name":"Joker","addr":"http:///"}
addResource result is : {"id":"NO2","name":"Joker","addr":"http://"}
getAllResource result is : [{"id":"NO2","name":"Joker","addr":"http://"}]

(2)HttpURLConnection

package com.restful.client;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.restful.entity.PersonEntity;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**

  • Created by XuHui on 2017/8/7.
    */
    public class HttpURLClient {
    private static String REST_API = “http://localhost:8080/jerseyDemo/rest/JerseyService”;

    public static void main(String[] args) throws Exception {
    addResource();
    getAllResource();
    }

    public static void addResource() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    URL url = new URL(REST_API + “/addResource/person”);
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setDoOutput(true);
    httpURLConnection.setRequestMethod(“POST”);
    httpURLConnection.setRequestProperty(“Accept”, “application/json”);
    httpURLConnection.setRequestProperty(“Content-Type”, “application/json”);
    PersonEntity entity = new PersonEntity(“NO2”, “Joker”, “http://”);
    OutputStream outputStream = httpURLConnection.getOutputStream();
    outputStream.write(mapper.writeValueAsBytes(entity));
    outputStream.flush();

     BufferedReader reader </span>= <span style="color: #0000ff;">new</span> BufferedReader(<span style="color: #0000ff;">new</span><span style="color: #000000;"> InputStreamReader(httpURLConnection.getInputStream()));
     String output;
     System.out.print(</span>"addResource result is : "<span style="color: #000000;">);
     </span><span style="color: #0000ff;">while</span> ((output = reader.readLine()) != <span style="color: #0000ff;">null</span><span style="color: #000000;">) {
         System.out.print(output);
     }
     System.out.print(</span>"\n"<span style="color: #000000;">);
    

    }

    public static void getAllResource() throws Exception {
    URL url = new URL(REST_API + “/getAllResource”);
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setRequestMethod(“GET”);
    httpURLConnection.setRequestProperty(“Accept”, “application/json”);
    BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
    String output;
    System.out.print(“getAllResource result is :”);
    while ((output = reader.readLine()) != null) {
    System.out.print(output);
    }
    System.out.print("\n");
    }

}

结果:

addResource result is : {"id":"NO2","name":"Joker","addr":"http://"}
getAllResource result is :[{"id":"NO2","name":"Joker","addr":"http://"}]

(3)HttpClient

package com.restful.client;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.restful.entity.PersonEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/**

  • Created by XuHui on 2017/8/7.
    */
    public class RestfulHttpClient {
    private static String REST_API = “http://localhost:8080/jerseyDemo/rest/JerseyService”;

    public static void main(String[] args) throws Exception {
    addResource();
    getAllResource();
    }

    public static void addResource() throws Exception {
    HttpClient httpClient = new DefaultHttpClient();
    PersonEntity entity = new PersonEntity(“NO2”, “Joker”, “http://”);
    ObjectMapper mapper = new ObjectMapper();

     HttpPost request </span>= <span style="color: #0000ff;">new</span> HttpPost(REST_API + "/addResource/person"<span style="color: #000000;">);
     request.setHeader(</span>"Content-Type", "application/json"<span style="color: #000000;">);
     request.setHeader(</span>"Accept", "application/json"<span style="color: #000000;">);
     StringEntity requestJson </span>= <span style="color: #0000ff;">new</span> StringEntity(mapper.writeValueAsString(entity), "utf-8"<span style="color: #000000;">);
     requestJson.setContentType(</span>"application/json"<span style="color: #000000;">);
     request.setEntity(requestJson);
     HttpResponse response </span>=<span style="color: #000000;"> httpClient.execute(request);
     String json </span>=<span style="color: #000000;"> EntityUtils.toString(response.getEntity());
     System.out.print(</span>"addResource result is : " + json + "\n"<span style="color: #000000;">);
    

    }

    public static void getAllResource() throws Exception {
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet request = new HttpGet(REST_API + “/getAllResource”);
    request.setHeader(“Content-Type”, “application/json”);
    request.setHeader(“Accept”, “application/json”);
    HttpResponse response = httpClient.execute(request);
    String json = EntityUtils.toString(response.getEntity());
    System.out.print("getAllResource result is : " + json + “\n”);
    }
    }

结果:

addResource result is : {"id":"NO2","name":"Joker","addr":"http://"}
getAllResource result is : [{"id":"NO2","name":"Joker","addr":"http://"}]

maven:

<dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.1.2</version>
</dependency>

(4)JAX-RS API

package com.restful.client;

import com.restful.entity.PersonEntity;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;

/**

  • Created by XuHui on 2017/7/27.
    */
    public class RestfulClient {
    private static String REST_API = “http://localhost:8080/jerseyDemo/rest/JerseyService”;
    public static void main(String[] args) throws Exception {
    getRandomResource();
    addResource();
    getAllResource();
    }

    public static void getRandomResource() throws IOException {
    Client client = ClientBuilder.newClient();
    client.property(“Content-Type”,“xml”);
    Response response = client.target(REST_API + “/getRandomResource”).request().get();
    String str = response.readEntity(String.class);
    System.out.print("getRandomResource result is : " + str + “\n”);
    }

    public static void addResource() {
    Client client = ClientBuilder.newClient();
    PersonEntity entity = new PersonEntity(“NO2”, “Joker”, “http://”);
    Response response = client.target(REST_API + “/addResource/person”).request().buildPost(Entity.entity(entity, MediaType.APPLICATION_JSON)).invoke();
    String str = response.readEntity(String.class);
    System.out.print("addResource result is : " + str + “\n”);
    }

    public static void getAllResource() throws IOException {
    Client client = ClientBuilder.newClient();
    client.property(“Content-Type”,“xml”);
    Response response = client.target(REST_API + “/getAllResource”).request().get();
    String str = response.readEntity(String.class);
    System.out.print("getAllResource result is : " + str + “\n”);

    }
    }

结果:

getRandomResource result is : {"id":"NO1","name":"Joker","addr":"http:///"}
addResource result is : {"id":"NO2","name":"Joker","addr":"http://"}
getAllResource result is : [{"id":"NO2","name":"Joker","addr":"http://"}]

(5)webClient

package com.restful.client;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.restful.entity.PersonEntity;
import org.apache.cxf.jaxrs.client.WebClient;

import javax.ws.rs.core.Response;

/**

  • Created by XuHui on 2017/8/7.
    */
    public class RestfulWebClient {
    private static String REST_API = “http://localhost:8080/jerseyDemo/rest/JerseyService”;
    public static void main(String[] args) throws Exception {
    addResource();
    getAllResource();
    }

    public static void addResource() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    WebClient client = WebClient.create(REST_API)
    .header(“Content-Type”, “application/json”)
    .header(“Accept”, “application/json”)
    .encoding(“UTF-8”)
    .acceptEncoding(“UTF-8”);
    PersonEntity entity = new PersonEntity(“NO2”, “Joker”, “http://”);
    Response response = client.path("/addResource/person").post(mapper.writeValueAsString(entity), Response.class);
    String json = response.readEntity(String.class);
    System.out.print("addResource result is : " + json + “\n”);
    }

    public static void getAllResource() {
    WebClient client = WebClient.create(REST_API)
    .header(“Content-Type”, “application/json”)
    .header(“Accept”, “application/json”)
    .encoding(“UTF-8”)
    .acceptEncoding(“UTF-8”);
    Response response = client.path("/getAllResource").get();
    String json = response.readEntity(String.class);
    System.out.print("getAllResource result is : " + json + “\n”);
    }
    }

结果:

addResource result is : {"id":"NO2","name":"Joker","addr":"http://"}
getAllResource result is : [{"id":"NO2","name":"Joker","addr":"http://"}

maven:

<dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-bundle-jaxrs</artifactId>
      <version>2.7.0</version>
</dependency>

注:该jar包引入和jersey包引入有冲突,不能在一个工程中同时引用。

 

	</div>
	<div class = "postDesc">posted @ <span id="post-date">2017-08-07 19:07</span> <a href='https://www.cnblogs.com/jave1ove/'>JokerPig</a> 阅读(<span id="post_view_count">...</span>) 评论(<span id="post_comment_count">...</span>)  <a href ="https://i.cnblogs.com/EditPosts.aspx?postid=7300787" rel="nofollow">编辑</a> <a href="#" onclick="AddToWz(7300787);return false;">收藏</a></div>
</div>
<script type="text/javascript">var allowComments=true,cb_blogId=283216,cb_entryId=7300787,cb_blogApp=currentBlogApp,cb_blogUserGuid='73478903-0811-e611-9fc1-ac853d9f53cc',cb_entryCreatedDate='2017/8/7 19:07:00';loadViewCount(cb_entryId);var cb_postType=1;var isMarkdown=false;</script>
</div><!--end: forFlow -->
</div><!--end: mainContent 主体内容容器-->

<div id="sideBar">
	<div id="sideBarMain">

公告

		<div id="blog-calendar" style="display:none"></div><script type="text/javascript">loadBlogDefaultCalendar();</script>
		
		<div id="leftcontentcontainer">
			<div id="blog-sidecolumn"></div><script type="text/javascript">loadBlogSideColumn();</script>
		</div>
		
	</div><!--end: sideBarMain -->
</div><!--end: sideBar 侧边栏容器 -->
<div class="clear"></div>
</div><!--end: main -->
<div class="clear"></div>
<div id="footer">

Copyright ©2019 JokerPig

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值