---
title: "jersey学习之Get请求"
author: "annybz"
date: "2013-11-26T10:45:12Z"
tags: []
categories: ["移动开发"]
slug: "jersey-get"
draft: false
lastmod: "2013-11-26T10:46:30Z"
id: 1980781
url: "https://annybz.iteye.com/blog/1980781"
---

继昨天学习的jersey简单使用，今天进行了稍微深入一点的学习。
jersey客户端调用webresources的get服务。

jersey 相关jar的加入，web.xml的里面的配置，在上一篇 jersey 简单学习中已经有介绍。这里我们就直接分析服务端和客户端代码了。


我的服务地址： http://localhost:8080/jerseydemo

server端：包名依然是
cn.thinkjoy.jerseydemo.resources;

类名： HelloWorldRs

package cn.thinkjoy.jerseydemo.resources;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

@Path("{helloWorldRs}")
public class HelloWorldRs {
	Map<String, String> map = new HashMap<String, String>();

	public HelloWorldRs() {
		map.put("1", "111");
		map.put("2", "222");
		map.put("3", "333");
	}

	@GET
	@Path("/sayHello")
	@Produces(MediaType.TEXT_PLAIN)
	public String sayHelloByGet(@QueryParam("from") String fromValue,
			@Context HttpServletRequest request) {
		System.out.println(fromValue);
		return "hello world " + map.get(fromValue);
	}
}



客户端：package cn.thinkjoy.jerseydemo.client;

import javax.ws.rs.core.MultivaluedMap;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;

public class JerseyClient {
	
	//因为我在web.xml中配置的请求匹配是   /rest/*
//所以这里到项目的目录jerseydemo后需要加上  /rest
	String url = "http://localhost:8080/jerseydemo/rest";
	
	public static void main(String args) {
		new JerseyClient().sayHelloTest();
	}

	
	public void sayHelloTest(){
		
		//创建一个默认的client
		Client client = Client.create();
		//创建webresource
		WebResource webResource = client.resource(url+"/helloWorldRs/sayHello");
		//添加请求需要的参数
		MultivaluedMap<String, String>  queryParam= new MultivaluedMapImpl();
		queryParam.add("from", "1");
		
		String str = webResource.queryParams(queryParam).get(String.class);
		
		System.out.println(str);
		
	}
}


启动服务端之后，运行客户端程序，即得到答案：hello world 111


同样在浏览器上试一下：http://localhost:8080/jerseydemo/rest/helloWorldRs/sayHello?from=1  

也得到答案：  hello world 111