Home | 简体中文 | 繁体中文 | 杂文 | Search | ITEYE 博客 | OSChina 博客 | Facebook | Linkedin | 作品与服务 | Email

第 18 章 Jersey - RESTful Web Services in Java.

目录

18.1. Client
18.1.1. Maven 版本
18.1.2. GET 操作
18.1.3. GET + Auth 用户认证

https://jersey.java.net/

18.1. Client

18.1.1. Maven 版本

1.x

			
<!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-client -->
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-client</artifactId>
    <version>1.19.2</version>
</dependency>	
			
			

2.x 版本

			
<dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-client</artifactId>
    <version>2.23.2</version>
</dependency>		
			
			

两个版本差异非常大,本文的例子使用2.23.2

18.1.2. GET 操作

			
package cn.netkiller.jersey;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.client.ClientConfig;

public class JerseyClientGet {

	public static void main(String[] args) {

		ClientConfig clientConfig = new ClientConfig();

		Client client = ClientBuilder.newClient(clientConfig);
		WebTarget webTarget = client.target("http://inf.netkiller.cn").path("/list/json/2.html");

		Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
		Response response = invocationBuilder.get();

		System.out.println(response.getStatus());
		System.out.println(response.getStatusInfo());

		if (response.getStatus() == 200) {

			String output = response.readEntity(String.class);
			System.out.println(output);

		}

	}
}	
			
			

18.1.3. GET + Auth 用户认证

			
package cn.netkiller.jersey;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;

public class JerseyClientGetAuth {

	public static void main(String[] args) {

		ClientConfig clientConfig = new ClientConfig();

		HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("neo", "chen");
		clientConfig.register(feature);

		Client client = ClientBuilder.newClient(clientConfig);
		WebTarget webTarget = client.target("http://api.netkiller.cn/v1/withdraw/ping.json").path("");

		Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
		Response response = invocationBuilder.get();

		System.out.println(response.getStatus());
		System.out.println(response.getStatusInfo());

		if (response.getStatus() == 200) {

			String output = response.readEntity(String.class);
			System.out.println(output);

		}

	}
}
			
			
comments powered by Disqus