后端发送HTTP POST请求的代码

后端发送HTTP POST请求的代码:

 protected void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("com.tievd.servlet.DevArceQueryServlet.handleRequest()");
        JSONObject params = new JSONObject();
        params.put("status", "ON");
        params.put("appid", "黄毅123");
        params.put("appsecret", "通过1110");
        params.put("page_size", 3);
        params.put("page_index", 1);
        params.put("trade_id", "好123");
        //创建执行请求的HttpClient对象
        HttpClient client = HttpClients.createDefault();
        String url = "http://localhost:8080/OutDataApi/QuerysDeviceChannels";
        //创建post请求对象
        HttpPost post = new HttpPost(url);
        //创建StringEntity对象,并将参数封装到该对象中,注意必须设置编码格式,否则参数会乱码
        StringEntity entity = new StringEntity(params.toString(), "UTF-8");
        //将参数放入请求对象中
        post.setEntity(entity);
        //发送请求
        HttpResponse response = client.execute(post);

 if (response.getStatusLine().getStatusCode() == 200) {
            //获取返回的数据
            HttpEntity result = response.getEntity();
            String messageString = EntityUtils.toString(result, "UTF-8");
            System.out.println(messageString);
            JSONObject message = JSONObject.fromObject(messageString);
            
        }
    }

猜你喜欢

转载自blog.csdn.net/weixin_41913605/article/details/83930299