Java实现Http客户端服务端间通信

访问Http Post请求的代码示例,项目为spring boot框架,省略不重要的部分。

1、Post服务端代码

样例1:

    @RequestMapping(value ="/testDemo1",method = RequestMethod.POST,produces={"application/xml"})
    public @ResponseBody String testDemo1(@RequestBody String body) throws IOException 
    {
    	logger.info(body);    //通过@RequestBody 获取Post 的消息体内容,另外可自行了解@RequestParam、@RequestAttribute
    	return abc;
    }
样例2:
    @RequestMapping(value ="/testDemo",method = RequestMethod.POST,produces={"application/xml"})
    public @ResponseBody String flashSingalInterface(HttpServletRequest request, HttpServletResponse response) throws IOException 
    {
    	// 读取请求内容 ----直接从request中获取
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));  
        String line = null;  
        StringBuilder sb = new StringBuilder();  
        while((line = br.readLine())!=null){  
            sb.append(line);  
        }  
      
        // 将资料解码  
        String reqBody = sb.toString();  
        String result = URLDecoder.decode(reqBody, "utf-8");  //utf-8
        
        logger.info(result);
        
    	Map map = new HashMap();
    	map.put("resultCode", "200");
    	map.put("resultDesc", "nice try");
    	
    	logger.info(JacksonUtil.bean2Json(map));
    	return JacksonUtil.bean2Json(map);
    }

2、客户端代码:(网上很多样例可参考,代码大同小异,依赖的jar包可能略有区别,注意下就行)

样例1:使用httpclient-4.5.2.jar 、httpcore-4.4.1.jar里的方法

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

入参为 url地址、json字符串、编码方式。

    private static String sendPost(String url, String jsonParams, String encoding) throws ClientProtocolException, IOException
    {
	int statusCode = 0;
	String body = "";
	String resultCode = "";

	// 设置协议http和https对应的处理socket链接工厂的对象
	Registry socketFactoryRegistry = RegistryBuilder. create()
			.register("http", PlainConnectionSocketFactory.INSTANCE).build();

	PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
	HttpClients.custom().setConnectionManager(connManager);

	// 创建自定义的httpclient对象
	CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
	// 创建post方式请求对象
	HttpPost httpPost = new HttpPost(url);
	
	StringEntity uefEntity = new StringEntity(jsonParams, encoding);
	uefEntity.setContentType("application/json");

	// 设置参数到请求对象中
	httpPost.setEntity(uefEntity);

	// 执行请求操作,并拿到结果(同步阻塞)
	CloseableHttpResponse response = client.execute(httpPost);

	statusCode = response.getStatusLine().getStatusCode();

	if (200 != statusCode) 
	{
		resultCode = "-1";
		return resultCode;
	}

	// 获取结果实体
	HttpEntity entity = response.getEntity();
	if (entity != null)
	{
		// 按指定编码转换结果实体为String类型
		body = EntityUtils.toString(entity, encoding);
		resultCode = getJson(body);
	}
	EntityUtils.consume(entity);

	// 释放链接
	response.close();
	return resultCode;
}

    //解析json串,获取resultCode值
    private static String getJson(String body)
    {
	JSONObject obj = JSONObject.fromObject(body);	
	String resultCode = obj.getString("resultCode");
	return resultCode;
    }

PS:使用Jackson,注意依赖包要导全了,参考:https://blog.csdn.net/zengdeqing2012/article/details/52053832

主函数:

    public static void main(String[] args)
    {
    	String postUrl = "http://localhost:8080/testDemo";
    	String reqJson = "{'name':'zhnagsan','age':'你好'}";
    	try 
    	{
	    sendPost(postUrl, reqJson, "UTF-8");
	}
    	catch (IOException e) 
    	{
	    e.printStackTrace();
	}
    }


样例2:使用com.springsource.org.apache.commons.httpclient-3.1.0.3510.jar 里的方法

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;

入参为url、Map类型的消息体(代码里进行json封装)

private static void send2(String url, Map contentPara) throws IOException
{
	HttpClient client = new HttpClient();
	PostMethod httpPost = new PostMethod(url);	
	httpPost.setRequestHeader("Content-type", "text/xml; charset=utf-8");
//	httpPost.setRequestHeader("Content-Length", String.valueOf(reqHead.length()));
	
	BufferedReader br = null;	
	String content = JacksonUtil.bean2Json(contentPara);
	
	httpPost.setRequestEntity(new StringRequestEntity(content, "text/xml", "utf-8"));
	int returnCode = client.executeMethod(httpPost);
	// 请求成功
	if (returnCode == 200)
	{
		br = new BufferedReader(new InputStreamReader(httpPost.getResponseBodyAsStream(), "utf-8"));
		StringBuffer stb = new StringBuffer();
		String str = null;
		// 拼接json字符串 后续处理
		while ((str = br.readLine()) != null)
		{
		    stb.append(str);
		}
		System.out.println(stb);
	} 
	br.close();	
	return;
}

主函数:    

public static void main(String[] args){
    	String postUrl = "xxx";
    	Map map = new HashMap();
    	map.put("name", "zhangsan");
    	map.put("age", "你好");
    	try{
    	    send2(postUrl, map);
	} catch (IOException e) {
            e.printStackTrace();
	}
}

3、自定义Jackson 工具类

依赖 jackson-annotations-2.8.0.jar、jackson-core-2.8.6.jar、jackson-databind-2.8.6.jar 包

package xxx;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;  
public class JacksonUtil
{
	private static ObjectMapper objectMapper = null;

	private static void init()
	{
		objectMapper = new ObjectMapper();
	}
        //对象转成Json字符串
	public static String bean2Json(Object obj) throws JsonProcessingException 
	{
		if (objectMapper == null)
		{
			init();
		}
		return objectMapper.writeValueAsString(obj);
	}
	//字符串转成对象
	public static  T json2Bean(String str, Class type) throws JsonParseException, JsonMappingException, IOException 
	{
		if (objectMapper == null)
		{
			init();
		}
		return objectMapper.readValue(str, type);
	}
	
}

调用方式在前面的代码里有,自己测下就明白了。


你可能感兴趣的:(java,http)