HttpServlet推送数据

本文介绍了一种使用HTTP Post请求将消息推送到门户的方法。通过构造HTTP客户端并发送带有JSON格式的有效负载来实现这一过程。文章详细展示了如何设置HTTP请求头,并处理服务器返回的响应。
public static String portalPushMessage(String url,Info info) throws ServletException, IOException {
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		HttpPost posturl = new HttpPost(url);
	        String jsonSting = JSON.toJSONString(info);
	        StringEntity entity = new StringEntity(jsonSting, "UTF-8");
	        posturl.setEntity(entity);
	        posturl.setHeader("Content-Type", "application/json;charset=utf8");
	        // 响应模型
	        CloseableHttpResponse response = null;
	        try {
                    // 由客户端执行(发送)Post请求
                    response = httpClient.execute(posturl);
                    // 从响应模型中获取响应实体
                    HttpEntity responseEntity = response.getEntity();
                    // 获取状态值
                    int code = response.getStatusLine().getStatusCode();
                    if (code != 200) {
                        return "fail1";
                    }else {
                        String line=null;
                        StringBuilder entityStringBuilder=new StringBuilder();
                        BufferedReader b = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"),8*1024);
                        while ((line=b.readLine())!=null) {
                	    entityStringBuilder.append(line);
                        }
                        JSONObject object = JSONObject.parseObject(entityStringBuilder.toString());  
                        int returncode = 0;
                        if(object.get("code") instanceof Integer) {
                	    returncode = (Integer) object.get("code");
                        }
                        if(returncode!=2) {
                	    return "fail2";
                        }
                    }
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                    return "fail1";
                } catch (Exception e) {
                    e.printStackTrace();
                    return "fail1";
                } finally {
                    try {
                        // 释放资源
                        if (httpClient != null) {
                            httpClient.close();
                        }
                        if (response != null) {
                            response.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
	    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值