欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

基于Restful接口調(diào)用方法總結(jié)(超詳細(xì))

 更新時(shí)間:2017年08月08日 09:17:40   投稿:jingxian  
下面小編就為大家?guī)?lái)一篇基于Restful接口調(diào)用方法總結(jié)(超詳細(xì))。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

由于在實(shí)際項(xiàng)目中碰到的restful服務(wù),參數(shù)都以json為準(zhǔn)。這里我獲取的接口和傳入的參數(shù)都是json字符串類型。發(fā)布restful服務(wù)可參照文章 Jersey實(shí)現(xiàn)Restful服務(wù)(實(shí)例講解),以下接口調(diào)用基于此服務(wù)。

基于發(fā)布的Restful服務(wù),下面總結(jié)幾種常用的調(diào)用方法。

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

結(jié)果:

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 = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
  String output;
  System.out.print("addResource result is : ");
  while ((output = reader.readLine()) != null) {
   System.out.print(output);
  }
  System.out.print("\n");
 }

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

}

結(jié)果:

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 = new HttpPost(REST_API + "/addResource/person");
  request.setHeader("Content-Type", "application/json");
  request.setHeader("Accept", "application/json");
  StringEntity requestJson = new StringEntity(mapper.writeValueAsString(entity), "utf-8");
  requestJson.setContentType("application/json");
  request.setEntity(requestJson);
  HttpResponse response = httpClient.execute(request);
  String json = EntityUtils.toString(response.getEntity());
  System.out.print("addResource result is : " + json + "\n");
 }

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

結(jié)果:

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");

 }
}

結(jié)果:

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

結(jié)果:

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包引入有沖突,不能在一個(gè)工程中同時(shí)引用。

以上這篇基于Restful接口調(diào)用方法總結(jié)(超詳細(xì))就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 聊聊SpringBoot自動(dòng)裝配的魔力

    聊聊SpringBoot自動(dòng)裝配的魔力

    這篇文章主要介紹了SpringBoot自動(dòng)裝配的魔力,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • 深入講解Java中的流程控制與運(yùn)算符

    深入講解Java中的流程控制與運(yùn)算符

    這篇文章主要介紹了Java中的流程控制與運(yùn)算符,是Java入門學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下
    2015-09-09
  • 詳解ZXing-core生成二維碼的方法并解析

    詳解ZXing-core生成二維碼的方法并解析

    本文給大家介紹ZXing-core生成二維碼的方法并解析,主要用到goggle發(fā)布的jar來(lái)實(shí)現(xiàn)二維碼功能,對(duì)此文感興趣的朋友一起學(xué)習(xí)吧
    2016-05-05
  • SpringBoot實(shí)現(xiàn)接口數(shù)據(jù)的加解密功能

    SpringBoot實(shí)現(xiàn)接口數(shù)據(jù)的加解密功能

    這篇文章主要介紹了SpringBoot實(shí)現(xiàn)接口數(shù)據(jù)的加解密功能,對(duì)接口的加密解密操作主要有兩種實(shí)現(xiàn)方式,文中給大家詳細(xì)介紹,需要的朋友可以參考下
    2019-10-10
  • java long轉(zhuǎn)String +Codeforces110A案例

    java long轉(zhuǎn)String +Codeforces110A案例

    這篇文章主要介紹了java long轉(zhuǎn)String +Codeforces110A案例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-09-09
  • 詳解JAVA 設(shè)計(jì)模式之狀態(tài)模式

    詳解JAVA 設(shè)計(jì)模式之狀態(tài)模式

    這篇文章主要介紹了JAVA 狀態(tài)模式的的相關(guān)資料,文中講解的非常細(xì)致,幫助大家更好的學(xué)習(xí)理解JAVA 設(shè)計(jì)模式,感興趣的朋友可以了解下
    2020-06-06
  • JVM方法調(diào)用invokevirtual詳解

    JVM方法調(diào)用invokevirtual詳解

    JVM調(diào)用方法有五條指令,分別是invokestatic,invokespecial,invokevirtual,invokeinterface,invokedynamic,這篇文章主要說(shuō)明invokevirtual方法的調(diào)用問(wèn)題,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧
    2022-03-03
  • Spring?Boot?中starter的原理詳析

    Spring?Boot?中starter的原理詳析

    這篇文章主要介紹了Spring?Boot?中starter原理詳析,文章圍繞主題展開(kāi)springboot的插件機(jī)制和starter原理相關(guān)資料,需要的小伙伴可以參考一下
    2022-06-06
  • 一文詳解Spring Security的基本用法

    一文詳解Spring Security的基本用法

    Spring Security是一個(gè)功能強(qiáng)大且高度可定制的身份驗(yàn)證和訪問(wèn)控制框架, 提供了完善的認(rèn)證機(jī)制和方法級(jí)的授權(quán)功能。本文將通過(guò)一個(gè)簡(jiǎn)單的案例了解一下Spring Security的基本用法,需要的可以參考一下
    2022-05-05
  • Java中@JSONField和@JsonProperty注解的用法及區(qū)別詳解

    Java中@JSONField和@JsonProperty注解的用法及區(qū)別詳解

    @JsonProperty和@JSONField注解都是為了解決obj轉(zhuǎn)json字符串的時(shí)候,將java bean的屬性名替換成目標(biāo)屬性名,下面這篇文章主要給大家介紹了關(guān)于Java中@JSONField和@JsonProperty注解的用法及區(qū)別的相關(guān)資料,需要的朋友可以參考下
    2024-06-06

最新評(píng)論