最近开发接口,调用的时候发现只有最原始的HttpServletRequest.getReader和getInputStream可以获取到,写了一套接口以及调用方法,日后学习了更多的东西再来补充
使用到的工具 JDK 1.8 , tomcat 7.0 , Apache HttpClient 4.5.5 , fastJson 1.2.47
分别写了Content-Type=text/plain(默认),Content-Type=application/xx-www-form-urlencoded以及
Content-Type=application/json,调用方法分别有key-value,String以及json格式
废话不多说,上代码
首先是springMVC写的接口类
package com.java.test.controller;
import java.io.BufferedReader;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.java.test.bean.ResName;
@Controller
public class HttpClientS {
Logger logger = Logger.getLogger(HttpClientS.class);
//Content-type : text/plain
@RequestMapping(value="/text",method=RequestMethod.POST)
public @ResponseBody String toText(HttpServletRequest request,HttpServletResponse response){
BufferedReader reader = null;
try {
reader = request.getReader();
StringBuffer buffer = new StringBuffer();
String line;
while((line = reader.readLine()) != null){
buffer.append(line);
}
//得到结果
String res = buffer.toString();
logger.info("text/plain传参:" + res);
//返回结果
return "{\"header\":{\"version\":\"1.0\",\"code\":\"1000\":\"message\":\"传输成功\"},\"body\":{\"param\":" + res + "}}";
} catch (Exception e) {
return "{\"header\":{\"version\":\"1.0\",\"code\":\"1001\":\"message\":\"传输失败\"}}";
}finally{
if(reader != null){
try {
reader.close();
} catch (IOException e) {
}
}
}
}
//Content-type : application/xx-www-form-urlencoded
@RequestMapping(value="/app",method=RequestMethod.POST)
public @ResponseBody String toApp(@RequestParam String name){
logger.info(name);
return "{\"header\":{\"version\":\"1.0\",\"code\":\"1000\":\"message\":\"传输成功\"},\"body\":{\"param\":" + name + "}}";
}
//Content-type : application/xx-www-form-urlencoded
@RequestMapping(value="/appBean",method=RequestMethod.POST)
public @ResponseBody String toAppBean(@RequestParam ResName name){
logger.info(name.getName());
return "{\"header\":{\"version\":\"1.0\",\"code\":\"1000\":\"message\":\"传输成功\"},\"body\":{\"param\":" + name.getName() + "}}";
}
//Content-type : application/json
@RequestMapping(value="/json",method=RequestMethod.POST)
public @ResponseBody String toJson(@RequestBody String json){
logger.info(json);
return "{\"header\":{\"version\":\"1.0\",\"code\":\"1000\":\"message\":\"传输成功\"},\"body\":{\"param\":" + json + "}}";
}
}
然后是HttpClient写的post方法
package com.java.utils;
import java.io.IOException;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONObject;
/**
* 基于Apache HttpClient插件调用http接口
*/
public class ClientPost {
public static String HttpClientPost(String url,String req){
CloseableHttpClient httpClient = null;
String str = "";
try {
//设定各种超时时间,可不加
// RequestConfig requestConfig = RequestConfig.custom()
// .setConnectTimeout(3000).setConnectionRequestTimeout(3000)
// .setSocketTimeout(3000).setRedirectsEnabled(true).build();
//创建可关闭的httpclient
httpClient = HttpClients.createDefault();
//如果使用get传值这里就是HttpGet()
HttpPost httpPost = new HttpPost(url);
/*采用默认header设置*/
//防止乱码(传入String格式的请求参数)
httpPost.setEntity(new StringEntity(req,"UTF-8"));
//把超时设定加入post
// httpPost.setConfig(requestConfig);
CloseableHttpResponse response = httpClient.execute(httpPost);
//判断调用是否成功
if(response.getStatusLine().getStatusCode() == 200){
str = EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
}finally{
//关闭httpClient
if(httpClient != null){
try {
httpClient.close();
} catch (IOException e) {
}
}
}
return str;
}
public static String HttpClientPost1(String url,List<NameValuePair> list){
CloseableHttpClient httpClient = null;
String str = "";
try {
//设定各种超时时间,可不加
// RequestConfig requestConfig = RequestConfig.custom()
// .setConnectTimeout(3000).setConnectionRequestTimeout(3000)
// .setSocketTimeout(3000).setRedirectsEnabled(true).build();
//创建可关闭的httpclient
httpClient = HttpClients.createDefault();
//如果使用get传值这里就是HttpGet()
HttpPost httpPost = new HttpPost(url);
/*设置header*/
httpPost.setHeader("Content-type","application/x-www-form-urlencoded;charset=UTF-8");
//防止乱码(传入List<NameValuePair>格式的请求参数)
httpPost.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));
//把超时设定加入post
// httpPost.setConfig(requestConfig);
CloseableHttpResponse response = httpClient.execute(httpPost);
//判断调用是否成功
if(response.getStatusLine().getStatusCode() == 200){
str = EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
}finally{
//关闭httpClient
if(httpClient != null){
try {
httpClient.close();
} catch (IOException e) {
}
}
}
return str;
}
public static String HttpClientPost2(String url,JSONObject json){
CloseableHttpClient httpClient = null;
String str = "";
try {
//设定各种超时时间,可不加
// RequestConfig requestConfig = RequestConfig.custom()
// .setConnectTimeout(3000).setConnectionRequestTimeout(3000)
// .setSocketTimeout(3000).setRedirectsEnabled(true).build();
//创建可关闭的httpclient
httpClient = HttpClients.createDefault();
//如果使用get传值这里就是HttpGet()
HttpPost httpPost = new HttpPost(url);
/*设置header*/
httpPost.setHeader("Content-type","application/json;charset=UTF-8");
httpPost.setHeader("Accept","application/json");
//防止乱码(传入Strng格式的请求参数)
httpPost.setEntity(new StringEntity(json.toJSONString(),"UTF-8"));
//把超时设定加入post
// httpPost.setConfig(requestConfig);
CloseableHttpResponse response = httpClient.execute(httpPost);
//判断调用是否成功
if(response.getStatusLine().getStatusCode() == 200){
str = EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
}finally{
//关闭httpClient
if(httpClient != null){
try {
httpClient.close();
} catch (IOException e) {
}
}
}
return str;
}
}
最后是调用post方法的测试类
package com.java.test;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.junit.Test;
import com.alibaba.fastjson.JSONObject;
import com.java.utils.ClientPost;
public class HttpTest {
private String textUrl = "http://服务器ip:8080/abb/text";
private String appUrl = "http://服务器ip:8080/abb/app";
private String appBeanUrl = "http://服务器ip:8080/abb/appBean";
private String jsonUrl = "http://服务器ip:8080/abb/json";
//调用text/plain接口
@Test
public void getText(){
//采用String的传参
String result = ClientPost.HttpClientPost(textUrl, "UrlName123");
System.out.println(result);
}
//调用application/xx-www-form-urlencoded接口,采用字符串读取
@Test
public void getAppUrl(){
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("name", "UrlName123"));
String result = ClientPost.HttpClientPost1(appUrl, list);
System.out.println(result);
}
//调用application/xx-www-form-urlencoded接口,采用Bean对象的getset方法读取
@Test
public void getAppBeanUrl(){
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("name", "UrlName123"));
String result = ClientPost.HttpClientPost1(appBeanUrl, list);
System.out.println(result);
}
//调用application/json接口
@Test
public void getJsonUrl(){
JSONObject json = new JSONObject(true);
json.put("name", "UrlName123");
json.put("age", 10);
json.put("school", "XXX");
String result = ClientPost.HttpClientPost2(jsonUrl, json);
System.out.println(result);
}
}
调用方法和接口并不是固定的,比如getJsonUrl可以去调用text接口,因为HttpServletRequest.getReader这几种格式都可以读取
后面写了multipart/form-datal我再放上来