httpclient的json传送数据调用

httpClient以post方式发送数据包:

public class aaa {
    public static void main(String[] args) {

          String formNo = "TR123456";
          HashMap<String, Object> notifyInfo = new HashMap<String, Object>();
          String time = String.valueOf(System.currentTimeMillis());
          String asz_access_key = "xxx";
          String content = formNo+time+asz_access_key;
          try {
              String sign = getBASE64Encoder(content);
              notifyInfo.put("referenceNo", formNo);
              notifyInfo.put("time", time);
              notifyInfo.put("sign", sign);
              } catch (Exception e) 
            {
                e.printStackTrace();
            } 
        //本地启动tomcat,调用本地tomcat接受数据
        boolean resultJSON = postJson("http://localhost:8080/testServlet1/MyFirstServlet", notifyInfo);
        System.out.println(resultJSON);

    }

    /**
     * sign加密
     * @return
     * @throws NoSuchAlgorithmException 
     * @throws UnsupportedEncodingException 
     */
    private static String  getBASE64Encoder(String content) throws NoSuchAlgorithmException, UnsupportedEncodingException{
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] bytes = md.digest(content.getBytes("UTF-8"));
        BASE64Encoder base64Encoder = new BASE64Encoder();
        return base64Encoder.encode(bytes);
    }

    /**
     * 以post方式调用httpClient
     * @param uri
     * @param param
     * @return
     */
    public static boolean postJson(String uri, HashMap<String, Object> param) {
        try {  
            CloseableHttpClient httpclient = HttpClients.createDefault();  
            HttpPost httpPost = new HttpPost(uri);   
            //添加http头信息  
            httpPost.addHeader("Content-Type", "application/json");  
            //设置字符集utf-8
            httpPost.getParams().setParameter( "http.protocol.content-charset","utf-8");
            //把数据改为String格式
            String stringObj = JSONObject.toJSONString(param);
            //封装数据
            httpPost.setEntity(new StringEntity(stringObj));     
            //执行调用,返回response
            CloseableHttpResponse response  = httpclient.execute(httpPost);  
            //检验状态码,如果成功接收数据  
            int code = response.getStatusLine().getStatusCode();  
            if (code == 200) {
                return true;
            } 
            }  catch (Exception e) { 
            }
            return false;  
    }
}

服务器方搭建tomcat环境,用servlet接受数据包:


/**
 * Servlet implementation class testServlet1
 */
@WebServlet(name
         = "MyFirstServlet",
         urlPatterns = {"/MyFirstServlet"})
public class testServlet1 extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public testServlet1() {
        super();
        System.out.println("getgetget");
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         request.setCharacterEncoding("UTF-8");
            //设置可以在页面中响应的内容类型及中文
            response.setContentType("text/html;charset=UTF-8");
            // 接收数据
            ServletInputStream in = request.getInputStream();
            // 这里是前台发起的所有参数的值,包括二进制形式的文件和其它形式的文件
            String str = readLine(in);
            System.out.println(str);
    }

     private static String readLine(ServletInputStream in) throws IOException {
          byte[] buf = new byte[8 * 1024];
          StringBuffer sbuf = new StringBuffer();
          int result;

          do {
           result = in.readLine(buf, 0, buf.length); // does +=
           if (result != -1) {
            sbuf.append(new String(buf, 0, result, "UTF-8"));
           }
          } while (result == buf.length); // loop only if the buffer was filled

          if (sbuf.length() == 0) {
           return null; // nothing read, must be at the end of stream
          }

          int len = sbuf.length();
          if (sbuf.charAt(len - 2) == '\r') {
           sbuf.setLength(len - 2); // cut \r\n
          } else {
           sbuf.setLength(len - 1); // cut \n
          }
          return sbuf.toString();
         }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值