Java HttpPost请求,并且是Bearer验证

依赖:


	com.alibaba
	fastjson
	1.2.78


	org.apache.httpcomponents
	httpclient
	4.5.13

请求方法:

   private static  String sendPost(String url,String jsonMap, String token) throws IOException {
        // 用于保存第三方公司定义的json格式的返回结果数据
        String result = "";

        // 创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();

        // 创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);

        // 头部携带的token
        if (token != null && !token.equals("")) {
            // 设置token,其中U-Token 是第三方(接口作者)定义的token名
            httpPost.setHeader("Authorization", "Bearer " + token);
        }

        // 设置参数到请求对象中
        StringEntity entity = new StringEntity(jsonMap, "UTF-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);

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

        if (response.getStatusLine().getStatusCode() == 200) {
            // 网络连接正常,将结果赋给result对象,此时result 对象保存的就是第三方公司定义的json格式的返回结果数据
            result = EntityUtils.toString(response.getEntity(), "UTF-8");
        }

        // 释放链接
        response.close();

        return result;
    }

测试:

    public static void main(String[] args)throws IOException {
	
        String json= "{\n" +
                "  \"FBillNo\": \"SVCD20230718001\",\n" +
                "  \"Status\": \"OPEN\"\n" +
                "}";
        String token="XX";
        String ret= sendPost("https://Ip地址/api/UpdateTIStatusAsync",json,token);
        System.out.println(ret);

    }

你可能感兴趣的:(java,python,前端)