在工作中遇到了一个这样的问题:需要从一个controller里面用HttpClient去请求另一个controller,然后返回信息给前一个controller,最后再返回给其它调用者。
HttpClient jar
<!-- httpClient jar -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.1</version>
</dependency>
简单demo示例:
1.HttpClientUtil工具类
package com.my.util;
import java.io.IOException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class HttpClientUtil {
//get方式
public static HttpResponse doGetRequest(String url) throws ClientProtocolException, IOException {
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Host", "getRequest");
httpGet.setHeader("auth", "token");
httpGet.setHeader("Accept-Language", "zh-cn,zh;q=0.5");
HttpResponse response = client.execute(httpGet);
Header[] headers = response.getAllHeaders();
System.out.println("-------------------------------");
for (Header header : headers) {
System.out.println(header.getName()+":"+header.getValue());
}
System.out.println("-------------------------------");
//获取返回信息
//HttpEntity entity = response.getEntity();
//String body = EntityUtils.toString(entity,"utf-8");
//这里不能return EntityUtile.toString(entity,"utf-8"); 会报IO错误
return response;
}
//post方式
public static HttpResponse doPostRequest(String url) throws ClientProtocolException, IOException {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setHeader("post", "doPostMethod");
HttpResponse response = client.execute(post);
return response;
}
// public static void main(String[] args) throws ClientProtocolException, IOException {
// HttpClientUtil.doGetRequest("http://localhost:8080/ssm/client/gettest");
// }
}
2.HttpClientController类,外部调用这个类,这个类再去调用对应的url
package com.my.controller;
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.my.util.HttpClientUtil;
@Controller
@RequestMapping(value="client")
public class HttpClientController {
@RequestMapping(value="/gettest",produces="application/json;charset=UTF-8")
@ResponseBody
public Map getTest(HttpServletRequest request,HttpServletResponse response) throws ClientProtocolException, IOException {
System.out.println(request.getHeader("auth")+"===auth");
Enumeration enumu = request.getHeaderNames();
while (enumu.hasMoreElements()) {
String name = (String) enumu.nextElement();
System.out.println(name+":"+request.getHeader(name));
}
// 设置content-type,只能在requestMapping里面设置,produces="application/json;charset=UTF-8"
// 设置响应头,下面这样是没有效果的
// response.setCharacterEncoding("utf-8");
// response.setContentType("text/html;charset=utf-8");
// response.setContentLength(90);
// response.setDateHeader("date", new Date().getTime());
// //添加响应头,添加不存在的响应头是有效果的
// response.addHeader("test", "test");
HttpResponse response2 = HttpClientUtil.doGetRequest("http://localhost:8080/ssm/userController");
String body = EntityUtils.toString(response2.getEntity(),"utf-8");
System.out.println(body+"hhhhhhhhhhhhhhhhhhhhhh");
Map<String, String> map = new HashMap<String, String>();
map.put("this", body);
return map;
}
@RequestMapping(value="/posttest",produces="application/json;charset=UTF-8")
@ResponseBody
public String postTest() throws ClientProtocolException, IOException {
String url = "http://localhost:8080/ssm/postTest";
HttpResponse response = HttpClientUtil.doPostRequest(url);
String body = EntityUtils.toString(response.getEntity(),"utf-8");
return body;
}
}
3.UserController类,被调用的类
package com.my.controller;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.my.entity.UserEntity;
import com.my.service.UserService;
/**
* restful风格测试
* @author 温文宪
*
*/
@Controller //或者Controller都可以
public class UserController {
// @Autowired
// private UserService service;
//
// @RequestMapping(value="/users/{id}",method=RequestMethod.PUT)
// @ResponseBody
// public UserEntity showEntity(@PathVariable("id")int idddd) {
// System.out.println(idddd);
// System.out.println(service.getDetailMessageById(idddd));
// return service.getDetailMessageById(idddd);
// }
//get方式测试
@RequestMapping(value="userController",produces="application/json;charset=UTF-8")
@ResponseBody
public Map<String, String> getTestMethod(HttpServletRequest request,HttpServletResponse response) {
Map<String, String> map = new HashMap<String, String>();
map.put("first", "nihao");
map.put("second", "women");
return map;
}
//post方式测试
@RequestMapping(value="postTest",produces="application/json;charset=UTF-8")
@ResponseBody
public Map postTestMethod() {
Map<String, String> map = new ConcurrentHashMap<>();
map.put("h1", "enen");
map.put("h2", "hehe");
return map;
}
}