java发送get以及post请求

1.依赖:

<dependency>  
  <groupId>com.github.wechatpay-apiv3</groupId>
    <artifactId>wechatpay-apache-httpclient</artifactId>
    <version>0.4.7</version>
</dependency>

2.代码: 

1.带参数的get请求(获取微信小程序的token为例子):
 

        // 请求url
        URIBuilder uriBuilder = new URIBuilder("https://api.weixin.qq.com/cgi-bin/token");
        // 设置参数
        uriBuilder.setParameter("grant_type","client_credential")
                .setParameter("appid","...")
                .setParameter("secret","...");

        URI build = uriBuilder.build();

        HttpGet httpGet = new HttpGet(build);
        // 是否要加这个,看情况而定
        httpGet.addHeader("Accept", "*/*");
        httpGet.addHeader("Content-type", "application/json; charset=utf-8");

        // 创建一个 CloseableHttpClient 对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 执行请求
        CloseableHttpResponse execute = httpClient.execute(httpGet);
        // 获取结果
        String responseBody = EntityUtils.toString(execute.getEntity());
        // 关闭连接
        execute.close();
        httpClient.close();
        // 获取token
        Map map = JSON.parseObject(responseBody, Map.class);


2.带参数的post请求(通过小程序检查一段文本是否含有违法违规内容为例子):

        // 请求url
        URIBuilder uriBuilder = new URIBuilder("https://api.weixin.qq.com/wxa/msg_sec_check");
        // 设置参数
        uriBuilder.setParameter("access_token",wxToekn);

        URI build = uriBuilder.build();

        HttpPost httpPost = new HttpPost(build);
        httpPost.addHeader("Accept", "application/json");
        httpPost.addHeader("Content-type", "application/json; charset=utf-8");

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectMapper objectMapper = new ObjectMapper();
        //组合请求参数JSON格式
        ObjectNode rootNode = objectMapper.createObjectNode();
        rootNode.put("openid", "openid")
                .put("scene", 2)
                .put("version", 2)
                .put("content", "要检测的文本");

        objectMapper.writeValue(bos, rootNode);
        httpPost.setEntity(new StringEntity(bos.toString("UTF-8"), "UTF-8"));

        // 创建一个 CloseableHttpClient 对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        CloseableHttpResponse response = httpClient.execute(httpPost);
        String bodyAsString = EntityUtils.toString(response.getEntity());

猜你喜欢

转载自blog.csdn.net/qq_26112725/article/details/133992335