Äú¿ÉÒÔ¾èÖú£¬Ö§³ÖÎÒÃǵĹ«ÒæÊÂÒµ¡£

1Ôª 10Ôª 50Ôª





ÈÏÖ¤Â룺  ÑéÖ¤Âë,¿´²»Çå³þ?Çëµã»÷Ë¢ÐÂÑéÖ¤Âë ±ØÌî



  ÇóÖª ÎÄÕ ÎÄ¿â Lib ÊÓÆµ iPerson ¿Î³Ì ÈÏÖ¤ ×Éѯ ¹¤¾ß ½²×ù Model Center   Code  
»áÔ±   
   
 
     
   
 ¶©ÔÄ
  ¾èÖú
Jersey¿ò¼Ü
 
  12408  次浏览      31
 2019-4-12  
 
±à¼­ÍƼö:
±¾ÎÄÀ´×ÔÓÚcnblogs,Ö÷Òª´ÓJersey RESTful WebService¿ò¼Ü¼ò½é£¬Jersey¶ÔJSONµÄÖ§³Ö£¬Jersey¶ÔHTTPSµÄÖ§³ÖµÈ·½ÃæÏêϸ½²½â¡£

Jersey RESTful WebService¿ò¼Ü¼ò½é

¿ª·¢RESTful WebServiceÒâζ×ÅÖ§³ÖÔÚ¶àÖÖýÌåÀàÐÍÒÔ¼°³éÏóµ×²ãµÄ¿Í»§¶Ë-·þÎñÆ÷ͨÐÅϸ½Ú£¬Èç¹ûûÓÐÒ»¸öºÃµÄ¹¤¾ß°ü¿ÉÓã¬Õ⽫ÊÇÒ»¸öÀ§ÄѵÄÈÎÎñ

ΪÁ˼ò»¯Ê¹ÓÃJava¿ª·¢RESTful WebService¼°Æä¿Í»§¶Ë£¬Ò»¸öÇáÁ¿¼¶µÄ±ê×¼±»Ìá³ö£ºJAX-RS API

Jersey RESTful WebService¿ò¼ÜÊÇÒ»¸ö¿ªÔ´µÄ¡¢²úÆ·¼¶±ðµÄJAVA¿ò¼Ü£¬Ö§³ÖJAX-RS API²¢ÇÒÊÇÒ»¸öJAX-RS(JSR 311ºÍ JSR 339)µÄ²Î¿¼ÊµÏÖ

Jersey²»½ö½öÊÇÒ»¸öJAX-RSµÄ²Î¿¼ÊµÏÖ£¬JerseyÌṩ×Ô¼ºµÄAPI£¬ÆäAPI¼Ì³Ð×ÔJAX-RS£¬Ìṩ¸ü¶àµÄÌØÐԺ͹¦ÄÜÒÔ½øÒ»²½¼ò»¯RESTful serviceºÍ¿Í»§¶ËµÄ¿ª·¢

Maven°æ±¾£º3.1.0

Jersey°æ±¾£º1.18

JDK°æ±¾£º1.7.0_65

Ò»£¬·þÎñ¶Ë

MavenÅäÖÃÈçÏ£º

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>JERSEY_SERVER</groupId>
<artifactId>JERSEY_SERVER</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.18</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-grizzly2</artifactId>
<version>1.18</version>
</dependency>
</dependencies>
</project>

 

Ê×ÏȽéÉܼ¸¸ö×¢½â£º

@Path

ÓÃÀ´Îª×ÊÔ´Àà»ò·½·¨¶¨ÒåURI£¬µ±È»³ýÁ˾²Ì¬URIÒ²Ö§³Ö¶¯Ì¬URI

@Path("service")
public class MyResource {
@Path("{sub_path}")
@GET
public String getResource(@PathParam("sub_path") String resourceName) {
......
Èç¹û´Ëʱ¿Í»§¶ËÇëÇóµÄU

 

Èç¹û´Ëʱ¿Í»§¶ËÇëÇóµÄURIΪhttp://127.0.0.1:10000/service/sean£¬Ôòsub_pathµÄֵΪsean

@PathParamÓÃÀ´½«ÇëÇóURIµÄÒ»²¿·Ö×÷Ϊ·½·¨²ÎÊý´«Èë·½·¨ÖÐ

¶ÔURIµÄ¶¯Ì¬²¿·Ö£¬¿ÉÒÔ×Ô¶¨ÒåУÑéÕýÔò±í´ïʽ£¬Èç¹ûÇëÇó²ÎÊýУÑéʧ°Ü£¬ÈÝÆ÷·µ»Ø404 Not Found

@Path("{sub_path:[A-Z]*}")

±íÃ÷±»×¢½âµÄ·½·¨ÏìÓ¦HTTP GETÇëÇó£¬@POST¡¢@PUTºÍ@DELETEͬÀí

@Consumes

¶¨ÒåÇëÇóµÄýÌåÀàÐÍ£¬Èç¹û²»Ö¸¶¨£¬ÔòÈÝÆ÷ĬÈϿɽÓÊÜÈÎÒâýÌåÀàÐÍ£¬ÈÝÆ÷¸ºÔðÈ·Èϱ»µ÷Óõķ½·¨¿É½ÓÊÜHTTPÇëÇóµÄýÌåÀàÐÍ£¬·ñÔò·µ»Ø415 Unsupported Media Type

·½·¨¼¶×¢½â½«¸²¸ÇÀ༶ע½â

@Produces

¶¨ÒåÏìӦýÌåÀàÐÍ£¬Èç¹û²»Ö¸¶¨£¬ÔòÈÝÆ÷ĬÈϿɽÓÊÜÈÎÒâýÌåÀàÐÍ£¬ÈÝÆ÷¸ºÔðÈ·Èϱ»µ÷Óõķ½·¨¿É·µ»ØHTTPÇëÇó¿ÉÒÔ½ÓÊÜýÌåÀàÐÍ£¬·ñÔò·µ»Ø406 Not Acceptable

·½·¨¼¶×¢½â½«¸²¸ÇÀ༶ע½â

@QueryParam

public String getResource(
@DefaultValue("Just a test!") @QueryParam("desc") String description) {
......
}

 

Èç¹ûÇëÇóURIÖаüº¬desc²ÎÊý£¬ÀýÈ磺http://127.0.0.1:10000/service/sean?desc=123456£¬Ôòdesc²ÎÊýµÄÖµ½«»á¸³¸ø·½·¨µÄ²ÎÊýdescription£¬·ñÔò·½·¨²ÎÊýdescriptionµÄÖµ½«Îª@DefaultValue×¢½â¶¨ÒåµÄĬÈÏÖµ

@Context

½«ÐÅÏ¢×¢ÈëÇëÇó»òÏìÓ¦Ïà¹ØµÄÀ࣬¿É×¢ÈëµÄÀàÓУºApplication£¬UriInfo£¬Request£¬HttpHeadersºÍSecurityContext

@SingletonºÍ@PerRequest

ĬÈÏÇé¿öÏ£¬×ÊÔ´ÀàµÄÉúÃüÖÜÆÚÊÇper-request£¬Ò²¾ÍÊÇϵͳ»áΪÿ¸öÆ¥Åä×ÊÔ´ÀàURIµÄÇëÇó´´½¨Ò»¸öʵÀý£¬ÕâÑùµÄЧÂʺܵͣ¬¿ÉÒÔ¶Ô×ÊÔ´ÀàʹÓÃ@Singleton×¢½â£¬ÕâÑùÔÚÓ¦Ó÷¶Î§ÄÚ£¬Ö»»á´´½¨×ÊÔ´ÀàµÄÒ»¸öʵÀý

·þÎñ¶Ë³ÌÐòÈçÏ£º

package com.sean;

import java.io.IOException;
import java.net.URI;
import java.util.Iterator;

import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;

import org.glassfish.grizzly.http.server.HttpServer;

import com.sun.jersey.api .container.grizzly2.GrizzlyServerFactory;
import com.sun.jersey.api .core.PackagesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;
import com.sun.jersey.spi.resource.Singleton;

@Singleton
@Path("service")
public class MyResource {

@Path("{sub_path:[a-zA-Z0-9]*}")
@GET
@Consumes ({MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON})
@Produces (MediaType.TEXT_PLAIN)
public String getResourceName(
@PathParam ("sub_path") String resourceName,
@DefaultValue ("Just a test!") @QueryParam("desc") String description,
@Context Request request,
@Context UriInfo uriInfo,
@Context HttpHeaders httpHeader) {
System.out.println (this.hashCode());

// ½«HTTPÇëÇó´òÓ¡³öÀ´
System.out.println ("****** HTTP request ******");
StringBuilder strBuilder = new StringBuilder();
strBuilder.append (request.getMethod() + " ");
strBuilder.append(uriInfo.getRequestUri().toString() + " ");
strBuilder.append("HTTP/1.1[\\r\\n]");
System.out.println (strBuilder.toString());
MultivaluedMap<String, String> headers = httpHeader.getRequestHeaders();
Iterator<String> iterator = headers.keySet().iterator();
while(iterator.hasNext()){
String headName = iterator.next();
System.out.println (headName + ":" + headers.get(headName) + "[\\r\\n]");
}
System.out.println ("[\\r\\n]");
String responseStr =resourceName + "[" + description + "]";
return responseStr;
}

public static void main (String[] args) {
URI uri = UriBuilder.fromUri ("http://127.0.0.1").port (10000).build();
ResourceConfig rc = new PackagesResourceConfig ("com.sean");
try {
HttpServer server = GrizzlyServerFactory.createHttpServer (uri, rc);
server.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(1000*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

 

¶þ£¬¿Í»§¶Ë

MavenÅäÖÃÈçÏ£º

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>JERSEY_CLIENT</groupId>
<artifactId>JERSEY_CLIENT</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.18</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-grizzly2</artifactId>
<version>1.18</version>
</dependency>
</dependencies>
</project>

 

¿Í»§¶Ë³ÌÐòÈçÏ£º

package com.sean;

import java.net.URI;
import java.util.Iterator;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriBuilder;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

public class JerseyClient {

public static void main(String[] args) {
// ҪʹÓÃJersey Client API£¬±ØÐëÊ×ÏÈ´´½¨ClientµÄʵÀý
// ÓÐÒÔÏÂÁ½ÖÖ´´½¨ClientʵÀýµÄ·½Ê½

// ·½Ê½Ò»
ClientConfig cc = new DefaultClientConfig();
cc.getProperties().put(ClientConfig.PROPERTY_CONNECT_TIMEOUT, 10*1000);
// ClientʵÀýºÜÏûºÄϵͳ×ÊÔ´£¬ÐèÒªÖØÓÃ
// ´´½¨web×ÊÔ´£¬´´½¨ÇëÇ󣬽ÓÊÜÏìÓ¦¶¼ÊÇḬ̈߳²È«µÄ
// ËùÒÔClientʵÀýºÍWebResourceʵÀý¿ÉÒÔÔÚ¶à¸öÏ̼߳䰲ȫµÄ¹²Ïí
Client client = Client.create(cc);

// ·½Ê½¶þ
// Client client = Client.create();
// client.setConnectTimeout(10*1000);
// client.getProperties().put (ClientConfig.PROPERTY _CONNECT_TIMEOUT, 10*1000);

// WebResource½«»á¼Ì³ÐClientÖÐtimeoutµÄÅäÖÃ
WebResource resource = client.resource("http://127.0.0.1:10000/ service/sean?desc =description");

String str = resource
.accept(MediaType.TEXT_PLAIN)
.type(MediaType.TEXT_PLAIN)
.get(String.class);
System.out.println("String:" + str);

URI uri = UriBuilder.fromUri ("http://127.0.0.1/service/sean" ).port(10000)
.queryParam ("desc", "description").build();
resource = client.resource(uri);

//header·½·¨¿ÉÓÃÀ´Ìí¼ÓHTTPÍ·
ClientResponse response = resource.header("auth", "123456")
.accept(MediaType.TEXT_PLAIN)
.type(MediaType.TEXT_PLAIN)
.get(ClientResponse.class);
// ½«HTTPÏìÓ¦´òÓ¡³öÀ´
System.out.println ("****** HTTP response ******");
StringBuilder strBuilder = new StringBuilder();
strBuilder.append ("HTTP/1.1 ");
strBuilder.append (response.getStatus() + " ");
strBuilder.append (response.getStatusInfo() + "[\\r\\n]");
System.out.println (strBuilder.toString());
MultivaluedMap<String, String> headers = response.getHeaders();
Iterator<String> iterator = headers.keySet().iterator();
while (iterator.hasNext()){
String headName = iterator.next();
System.out.println (headName + ":" + headers.get(headName) + "[\\r\\n]");
}
System.out.println ("[\\r\\n]");
System.out.println (response.getEntity(String.class) + "[\\r\\n]");
}
}

 

·þÎñ¶ËÈÕÖ¾ÈçÏ£º

¶þÔÂ 06, 2015 4:33:33 ÏÂÎç com.sun.jersey.api.core.PackagesResourceConfig init
INFO: Scanning for root resource and provider classes in the packages:
com.sean
¶þÔÂ 06, 2015 4:33:33 ÏÂÎç com.sun.jersey.api.core.ScanningResourceConfig logClasses
INFO: Root resource classes found:
class com.sean.Test
class com.sean.MyResource
¶þÔÂ 06, 2015 4:33:33 ÏÂÎç com.sun.jersey.api.core.ScanningResourceConfig init
INFO: No provider classes found.
¶þÔÂ 06, 2015 4:33:33 ÏÂÎç com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.18 11/22/2013 01:21 AM'
¶þÔÂ 06, 2015 4:33:34 ÏÂÎç org.glassfish.grizzly.http.server.NetworkListener start
INFO: Started listener bound to [127.0.0.1:10000]
¶þÔÂ 06, 2015 4:33:34 ÏÂÎç org.glassfish.grizzly.http.server.HttpServer start
INFO: [HttpServer] Started.

****** HTTP request ******
GET http://127.0.0.1:10000/service/sean?desc =description HTTP/1.1[\r\n]
accept:[text/plain][\r\n]
content-type:[text/plain][\r\n]
user-agent:[Java/1.7.0_65][\r\n]
host:[127.0.0.1:10000][\r\n]
connection:[keep-alive][\r\n]
[\r\n]

****** HTTP request ******
GET http://127.0.0.1:10000/service/sean?desc =description HTTP/1.1[\r\n]
auth:[123456][\r\n]
accept:[text/plain][\r\n]
content-type:[text/plain][\r\n]
user-agent:[Java/1.7.0_65][\r\n]
host:[127.0.0.1:10000][\r\n]
connection:[keep-alive][\r\n]
[\r\n]

 

¿Í»§¶ËÈÕÖ¾ÈçÏ£º

String:sean[description]
****** HTTP response ******
HTTP/1.1 200 OK[\r\n]
Transfer-Encoding:[chunked][\r\n]
Date:[Fri, 06 Feb 2015 08:33:38 GMT][\r\n]
Content-Type:[text/plain][\r\n]
[\r\n]
sean[description][\r\n]

Jersey¶ÔJSONµÄÖ§³Ö

JerseyÌṩ3ÖÖ»ù±¾·½Ê½À´Ê¹ÓÃJSON¸ñʽ

ÎÞÂÛʹÓúÎÖÖ·½Ê½£¬ÔÚÔ­ÓаüµÄ»ù´¡ÉÏ£¬¶¼ÐèÒªÔÚ¿Í»§¶ËºÍ·þÎñ¶ËMavenÅäÖÃÎļþÖÐÌí¼Ójersey-json°üÒÔÖ§³ÖJSON¸ñʽ

<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.18</version>
</dependency>

Ò»£¬»ùÓÚPOJO

RequestÀàºÍResponseÀࣨ·þÎñ¶ËºÍ¿Í»§¶Ë¶¼ÐèÒª£©¶¼ÊÇ»ù±¾µÄPOJO£º

package com.sean;

public class Request {
private String query;

public String getQuery() {
return query;
}

public void setQuery(String query) {
this.query = query;
}
}

package com.sean;

public class Response {
private int respCode;
private String respDesc;

public int getRespCode() {
return respCode;
}

public void setRespCode(int respCode) {
this.respCode = respCode;
}

public String getRespDesc() {
return respDesc;
}

public void setRespDesc(String respDesc) {
this.respDesc = respDesc;
}
}

 

·þÎñ¶Ë´úÂ룺

package com.sean;

import java.io.IOException;
import java.net.URI;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import org.glassfish.grizzly.http.server.HttpServer;

import com.sun.jersey.api.container .grizzly2.GrizzlyServerFactory;
import com.sun.jersey.api.core .PackagesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;
import com.sun.jersey .api.json.JSONConfiguration;

@Path("query")
public class MyResource {

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response query(Request req) {
System.out.println(req.getQuery());

Response resp = new Response();
resp.setRespCode(0);
resp.setRespDesc(req.getQuery());
return resp;
}

public static void main (String[] args) {
URI uri = UriBuilder.fromUri ("http://127.0.0.1" ).port(10000).build();
ResourceConfig rc = new PackagesResourceConfig ("com.sean");
//ʹÓÃJersey¶ÔPOJOµÄÖ§³Ö£¬±ØÐëÉèÖÃΪtrue
rc.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, true);
try {
HttpServer server = GrizzlyServerFactory.createHttpServer(uri, rc);
server.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(1000*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

¿Í»§¶Ë´úÂ룺

package com.sean;

import javax.ws.rs.core.MediaType;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;

public class JerseyClient {

public static void main (String[] args) {
ClientConfig cc = new DefaultClientConfig();
//ʹÓÃJersey¶ÔPOJOµÄÖ§³Ö£¬±ØÐëÉèÖÃΪtrue
cc.getFeatures().put (JSONConfiguration.FEATURE _POJO _MAPPING, Boolean.TRUE);
Client client = Client.create(cc);

WebResource resource = client.resource ("http://127.0.0.1:10000/query");

Request req = new Request();
req.setQuery ("name");

ClientResponse response = resource
.accept (MediaType.APPLICATION_JSON)
.type (MediaType.APPLICATION_JSON)
.post (ClientResponse.class, req);

Response resp = response.getEntity(Response.class);
System.out.println (resp.getRespCode() + " " + resp.getRespDesc());
}
}

¶þ£¬»ùÓÚJAXB

ʹÓÃJAXBµÄÓŵãÔÚÓÚ£¬ÎÞÂÛʹÓÃXML¸ñʽ»¹ÊÇJSON¸ñʽÊý¾Ý£¬¶¼¿ÉÒÔʹÓÃͳһµÄJavaÄ£ÐÍ

ȱµãºÜÄÑÕÒµ½Ò»¸öºÏÊʵķ½Ê½À´Éú³ÉÌØÊâµÄJSON¸ñʽ£¬ÕâÒ²ÊÇJerseyÌṩºÜ¶à¿ØÖÆÑ¡ÏîµÄÔ­Òò

½«RequestÀàºÍResponseÀà½øÐÐÐ޸ģº

package com.sean;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Request {
private String query;

public String getQuery() {
return query;
}

public void setQuery(String query) {
this.query = query;
}
}

package com.sean;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Response {
private int respCode;
private String respDesc;

public int getRespCode() {
return respCode;
}

public void setRespCode(int respCode) {
this.respCode = respCode;
}

public String getRespDesc() {
return respDesc;
}

public void setRespDesc(String respDesc) {
this.respDesc = respDesc;
}
}

·þÎñ¶Ë´úÂëÈ¥µôÏÂÃæµÄÅäÖÃ

// rc.getFeatures().put (JSONConfiguration.FEATURE _POJO_MAPPING, true);

¿Í»§¶Ë´úÂëÈ¥µôÏÂÃæµÄÅäÖÃ

// cc.getFeatures().put (JSONConfiguration.FEATURE _POJO_MAPPING, Boolean.TRUE);

JerseyÌṩºÜ¶à¿ØÖÆÑ¡ÏîÒÔ±ã¸ü¾«Ï¸µÄ¿ØÖÆJSONµÄ½âÎö¡¢×é×°¹ý³Ì£¬µ«ÊǾÍÎÒ¸öÈËÀ´¿´£¬JAXBÌṩµÄ±êÇ©×㹻ʹÓÃÁË

Èý£¬»ùÓڵײãJSONObject/JSONArray

×î´óµÄÓÅÊÆÔÚÓÚ¿ÉÒÔÍêÈ«¿ØÖÆJSONµÄ½âÎö¡¢×é×°¹ý³Ì£¬ÏàÓ¦µÄ£¬ÔÚ´¦ÀíÊý¾Ý¶ÔÏóʱҲҪ¸ü¸´ÔÓ

·þÎñ¶Ë´úÂëÈçÏ£º

package com.sean;

import java.io.IOException;
import java.net.URI;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.glassfish.grizzly.http.server.HttpServer;

import com.sun.jersey.api.container.grizzly2 .GrizzlyServerFactory;
import com.sun.jersey.api.core .PackagesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;

@Path("query")
public class MyResource {

@POST
@Consumes (MediaType.APPLICATION_JSON)
@Produce s(MediaType.APPLICATION_JSON)
public JSONObject query (JSONObject query) {
//{"query":"name"}
System.out.println (query.toString());

JSONObject resp = new JSONObject();
try {
resp.put("respCode", 0);
resp.put("respDesc", query.get("query"));
} catch (JSONException e) {
e.printStackTrace();
}
return resp;
}

public static void main (String[] args) {
URI uri = UriBuilder.fromUri ("http://127.0.0.1" ).port(10000).build();
ResourceConfig rc = new PackagesResourceConfig ("com.sean");
try {
HttpServer server = GrizzlyServerFactory.createHttpServer (uri, rc);
server.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(1000*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}


¿Í»§¶Ë´úÂëÈçÏ£º

package com.sean;

import javax.ws.rs.core.MediaType;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api. client.config.DefaultClientConfig;

public class JerseyClient {

public static void main(String[] args) {
ClientConfig cc = new DefaultClientConfig();
Client client = Client.create(cc);

WebResource resource = client.resource ("http://127.0.0.1:10000/query");

JSONObject req = new JSONObject();
try {
req.put ("query", "name");
} catch (JSONException e) {
e.printStackTrace();
}

ClientResponse response = resource
.accept (MediaType.APPLICATION_JSON)
.type (MediaType.APPLICATION_JSON)
.post (ClientResponse.class, req);

JSONObject resp = response.getEntity(JSONObject.class);
//{"respCode":0, "respDesc": "name"}
System.out.println(resp.toString());
}
}

ÓëJAXBÏà±È£¬½á¹ûÊÇÏàͬµÄ£¬µ«ÊÇ´¦Àí¹ý³Ì£¨Ö÷ÒªÊÇ×é×°JSON¶ÔÏó£©Òª¸´ÔÓ

¶ÔÓÚÉÏÃæ3ÖÖ·½Ê½£¬¾ù¿ÉʹÓÃStringÀà´úÌæRequestÀà¡¢ResponseÀà»òJSONObjectÀ࣬Jersey»á×Ô¶¯½«¶ÔÏóת»»ÎªJSON´®

µ±È»£¬Èç¹û¿Í»§¶ËÐÞ¸ÄΪString£¬·þÎñ¶ËÒ²ÒªÏàÓ¦µÄÐÞ¸ÄΪStringÀàÐÍ

Ð޸Ŀͻ§¶Ë´úÂ룺

public class JerseyClient {

public static void main(String[] args) {
ClientConfig cc = new DefaultClientConfig();
Client client = Client.create(cc);

WebResource resource = client.resource ("http://127.0.0.1:10000/query");

JSONObject req = new JSONObject();
try {
req.put("query", "name");
} catch (JSONException e) {
e.printStackTrace();
}

String response = resource
.accept(MediaType.APPLICATION_JSON)
.type(MediaType.APPLICATION_JSON)
.post(String.class, req.toString());
}
}

Jersey¶ÔHTTPSµÄÖ§³Ö

Ö¤ÊéµÄÉú³É¹ý³ÌÕâÀï¾Í²»½éÉÜÁË

´úÂë½á¹¹ÈçÏ£º

MavenÅäÖÃÎļþ£º

<project xmlns ="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/ 2001/XMLSchema-instance"
xsi:schemaLocation=" http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven -4.0.0.xsd">
<modelVersion> 4.0.0</modelVersion>
<groupId> JERSEY</groupId>
<artifactId> JERSEY</artifactId>
<version>1.0< /version>
<dependencies>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId> jersey-client</artifactId>
<version> 1.18</version>
</dependency>
<dependency>
<groupId> com.sun.jersey</groupId>
<artifactId> jersey-grizzly2</artifactId>
<version>1.18</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.18</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media </groupId>
<artifactId> jersey-media-json-jackson</artifactId>
<version> 2.15</version>
</dependency>
</dependencies>
</project>

PersonÀàÊÇ»ù±¾µÄJAXB£º

package com.sean;

import java.util.List;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Person {
private String name;
private List<String> addresses;

public Person(){}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public List<String> getAddresses() {
return addresses;
}

public void setAddresses(List<String> addresses) {
this.addresses = addresses;
}
}

¿Í»§¶Ë´úÂ룺

package com.sean;

import java.net.URI;

import javax.net.ssl.SSLContext;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import org.glassfish.jersey.SslConfigurator;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client .config.ClientConfig;
import com.sun.jersey.api.client .config.DefaultClientConfig;
import com.sun.jersey.client .urlconnection.HTTPSProperties;

public class SSLClient {
public static void main(String[] args) {
int authType =
Integer.valueOf (Config.getConfig().getProperty ("authority")).intValue();

SslConfigurator sslConfig = SslConfigurator.newInstance();
if(authType == 1){
sslConfig.trustStoreFile (Config.getConfig().getProperty ("clientTrustCer"))
.trustStorePassword (Config.getConfig().getProperty ("clientTrustCerPwd"));
}else if(authType == 2){
sslConfig.keyStoreFile (Config.getConfig().getProperty ("clientCer"))
.keyStorePassword (Config.getConfig().getProperty ("clientCerPwd"))
.keyPassword (Config.getConfig().getProperty ("clientKeyPwd"))
.trustStoreFile (Config.getConfig().getProperty ("clientTrustCer"))
.trustStorePassword (Config.getConfig().getProperty ("clientTrustCerPwd"));
}
sslConfig.securityProtocol (Config.getConfig().getProperty ("protocol"));
SSLContext sslContext = sslConfig.createSSLContext();

ClientConfig cc = new DefaultClientConfig();
cc.getProperties().put (HTTPSProperties.PROPERTY _HTTPS_PROPERTIES,
new HTTPSProperties (new MyHostnameVerifier(), sslContext));
Client client = Client.create(cc);

URI uri = UriBuilder.fromUri ("https://127.0.0.1/ queryAddress").port(10000).build();
WebResource resource = client.resource(uri);

Person person = new Person();
person.setName ("sean");

ClientResponse response = resource
.accept (MediaType.APPLICATION_XML)
.type (MediaType.APPLICATION_XML)
.post (ClientResponse.class, person);

String addresses = response.getEntity(String.class);
System.out.println (addresses);
}
}

SSLÎÕÊÖ¹ý³ÌÖУ¬»á¶ÔÇëÇóIP»òÇëÇóÓòÃû½øÐÐУÑ飬Èç¹ûÔÚÖ¤ÊéÐÅÏ¢ÖÐÎÞ·¨ÕÒµ½Ïà¹ØÇëÇóIP»òÇëÇóÓòÃûÔò»á±¨´í£¨javax.NET.ssl.SSLHandshakeException: Java.security.cert.CertificateException: No subject alternative names present£©

ÕâÀïʵÏÖ×Ô¼ºµÄУÑéÂß¼­£¨Èç¹ûÇëÇóµÄIPΪ127.0.0.1»òÇëÇóµÄÓòÃûΪlocalhost£¬ÔòÖ±½Óͨ¹ýУÑ飩ÒÔ¸²¸ÇĬÈÏÂß¼­

package com.sean;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

public class MyHostnameVerifier implements HostnameVerifier {

@Override
public boolean verify(String hostname, SSLSession session) {
if("127.0.0.1".equals(hostname) || "localhost".equals(hostname) )
return true;
else
return false;
}
}


·þÎñ¶Ë´úÂ룺

package com.sean;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.SSLContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import org.glassfish.grizzly.http.server.HttpHandler;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.grizzly.ssl.SSLEngineConfigurator;
import org.glassfish.jersey.SslConfigurator;

import com.sun.jersey.api.container .ContainerFactory;
import com.sun.jersey.api.container.grizzly2 .GrizzlyServerFactory;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;

@Path("queryAddress")
public class SSLServer {

@POST
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public Person queryAddress(String name) {
System.out.println(name);

Person person = new Person();
List<String> addresses = new ArrayList<String>();
addresses.add("address1");
addresses.add("address2");
person.setAddresses(addresses);
return person;
}

public static void main(String[] args) {
Integer authType =
Integer.valueOf (Config.getConfig().getProperty ("authority")).intValue();

SslConfigurator sslConfig = SslConfigurator.newInstance();
if(authType == 1){
sslConfig.keyStoreFile (Config.getConfig().getProperty ("serverCer"))
.keyStorePassword (Config.getConfig().getProperty ("serverCerPwd"))
.keyPassword (Config.getConfig().getProperty ("serverKeyPwd"));
}else if(authType == 2){
sslConfig.keyStoreFil e (Config.getConfig().getProperty ("serverCer"))
.keyStorePassword (Config.getConfig().getProperty ("serverCerPwd"))
.keyPassword (Config.getConfig().getProperty ("serverKeyPwd"))
.trustStoreFile (Config.getConfig().getProperty ("serverTrustCer"))
.trustStorePassword (Config.getConfig().getProperty ("serverTrustCerPwd"));
}
sslConfig.securityProtocol (Config.getConfig().getProperty ("protocol"));
SSLContext sslContext = sslConfig.createSSLContext();

SSLEngineConfigurator sslEngineConfig = new SSLEngineConfigurator (sslContext);
//ĬÈÏÇé¿öÏÂÊǿͻ§¶Ëģʽ£¬Èç¹ûÍü¼ÇÐÞ¸Äģʽ
//»áÅ׳öÒì³£
//javax.net.ssl.SSLProtocolException: Handshake message sequence violation, 1]
sslEngineConfig.setClientMode (false);
if(authType == 1)
sslEngineConfig .setWantClientAuth(true);
else if (authType == 2)
sslEngineConfig.setNeedClientAuth (true);

ResourceConfig rc = new PackagesResourceConfig ("com.sean");
HttpHandler handler = ContainerFactory.createContainer(
HttpHandler.class, rc);

URI uri = UriBuilder.fromUri ("https://127.0.0.1/") .port(10000).build();
try {
HttpServer server = GrizzlyServerFactory.createHttpServer (uri, handler, true,
sslEngineConfig);
server.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(1000*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

ÅäÖÃÎļþÀࣺ

package com.sean;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

public class Config{
private static Properties config;

public static Properties getConfig(){
try{
if(null == config){
File configFile =
new File ("src/main/resources/config/config.properties");
if(configFile.exists() && configFile.isFile()
&& configFile.canRead()){
InputStream input = new FileInputStream(configFile);
config = new Properties();
config.load(input);
}
}
}catch(Exception e){
//default set
config = new Properties();
config.setProperty ("authority", String.valueOf(1));
config.setProperty ("protocol", "SSL");
config.setProperty ("serverCer", "src/main/resources/certificate/server.jks");
config.setProperty ("serverCerPwd", "1234sp");
config.setProperty ("serverKeyPwd", "1234kp");
config.setProperty ("serverTrustCer", "src/main/resources/certificate/serverTrust.jks");
config.setProperty ("serverTrustCerPwd", "1234sp");
config.setProperty ("clientCer", "src/main/resources/certificate/client.jks");
config.setProperty ("clientCerPwd", "1234sp");
config.setProperty ("clientKeyPwd", "1234kp");
config.setProperty ("clientTrustCer", "src/main/resources/certificate/clientTrust.jks");
config.setProperty ("clientTrustCerPwd", "1234sp");
}
return config;
}
}

ÅäÖÃÎļþconfig.properties£º

#1£ºµ¥ÏòÈÏÖ¤£¬Ö»ÓзþÎñÆ÷¶ËÐèÖ¤Ã÷ÆäÉí·Ý
#2£ºË«ÏòÈÏÖ¤£¬·þÎñÆ÷¶ËºÍ¿Í»§¶Ë¶¼ÐèÖ¤Ã÷ÆäÉí·Ý
authority=2
#ͨÐÅЭÒé
protocol=SSL
#·þÎñ¶ËÖ¤ÊéÐÅÏ¢
serverCer= src/main/resources/certificate/server.jks
#keystoreµÄstorepass
serverCerPwd=1234sp
#keystoreµÄkeypass
serverKeyPwd= 1234kp
#·þÎñ¶ËÖ¤ÊéÐÅÏ¢
serverTrustCer= src/main/resources/certificate/serverTrust.jks
serverTrustCerPwd= 1234sp
#¿Í»§¶ËÖ¤ÊéÐÅÏ¢
clientCer= src/main/resources/certificate/client.jks
clientCerPwd= 1234sp
clientKeyPwd= 1234kp
clientTrustCer= src/main/resources/certificate/clientTrust.jks
clientTrustCerPwd=1234sp

·þÎñ¶ËÔËÐнá¹û£º

ÈýÔÂ 03, 2015 3:30:54 ÏÂÎç com.sun.jersey.api.core.PackagesResourceConfig init
INFO: Scanning for root resource and provider classes in the packages:
com.sean
ÈýÔÂ 03, 2015 3:30:54 ÏÂÎç com.sun.jersey.api.core.ScanningResourceConfig logClasses
INFO: Root resource classes found:
class com.sean.SSLServer
ÈýÔÂ 03, 2015 3:30:54 ÏÂÎç com.sun.jersey.api.core.ScanningResourceConfig init
INFO: No provider classes found.
ÈýÔÂ 03, 2015 3:30:54 ÏÂÎç com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.18 11/22/2013 01:21 AM'
ÈýÔÂ 03, 2015 3:30:55 ÏÂÎç org.glassfish.grizzly.http.server.NetworkListener start
INFO: Started listener bound to [127.0.0.1:10000]
ÈýÔÂ 03, 2015 3:30:55 ÏÂÎç org.glassfish.grizzly.http.server.HttpServer start
INFO: [HttpServer] Started.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><person><name>sean</name></person>

¿Í»§¶ËÔËÐнá¹û

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <person> <addresses>address1</addresses> <addresses>address2 </addresses></person>


   
12408 ´Îä¯ÀÀ       31
Ïà¹ØÎÄÕÂ

Java΢·þÎñÐÂÉú´úÖ®Nacos
ÉîÈëÀí½âJavaÖеÄÈÝÆ÷
JavaÈÝÆ÷Ïê½â
Java´úÂëÖÊÁ¿¼ì²é¹¤¾ß¼°Ê¹Óð¸Àý
Ïà¹ØÎĵµ

JavaÐÔÄÜÓÅ»¯
Spring¿ò¼Ü
SSM¿ò¼Ü¼òµ¥¼òÉÜ
´ÓÁ㿪ʼѧjava±à³Ì¾­µä
Ïà¹Ø¿Î³Ì

¸ßÐÔÄÜJava±à³ÌÓëϵͳÐÔÄÜÓÅ»¯
JavaEE¼Ü¹¹¡¢ Éè¼ÆÄ£Ê½¼°ÐÔÄܵ÷ÓÅ
Java±à³Ì»ù´¡µ½Ó¦Óÿª·¢
JAVAÐéÄâ»úÔ­ÀíÆÊÎö