java http 发送post请求-json格式

        最近项目中有向微信后台发送请求一些操作,网上的很多工具有问题,自己根据其中一个优化了一下,直接上代码:

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;


public static String doPost(String url, String json) {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(url);
    String result = null;
    try {
        StringEntity s = new StringEntity(json,"utf-8");
        s.setContentEncoding("UTF-8");
        s.setContentType("application/json");//发送json数据需要设置contentType
        post.setEntity(s);

        HttpResponse res = client.execute(post);
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            if (res.getEntity().isStreaming() && "image/jpeg".equals(res.getEntity().getContentType().getValue())){
                File file = new File("C:/Users/Administrator/Desktop/5.jpg");
                if (!file.exists()){
                    file.createNewFile();
                }
                OutputStream outputStream = new FileOutputStream(file);
                res.getEntity().writeTo(outputStream);
                outputStream.flush();
                return "ojbk";
            }
            result = EntityUtils.toString(res.getEntity());// 返回json格式:

        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {
            client.close();
        } catch (IOException e) {
            log.error("【post关闭】 异常IOException = ", e);
        }
    }
    return result;
}

        这里的参数json是json格式的字符串。

        如果有需要,可以根据返回的Content-Type做一些相应的处理。

        简单的用法,比如获取小程序的二维码向微信用户推送模板消息

    public static void main(String[] args) {
        String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=你的APPID&secret=你的APPSECRET";
        String s = UrlUtil.get(token_url);
        Map getResult = (Map) JSON.parse(s);
        String accessToken = (String) getResult.get("access_token");
        Map map = new HashMap();
        map.put("scene","310");
        map.put("page","pages/login/main");
        //获取小程序的二维码
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;
        String s1 = UrlUtil.doPost(url, JSON.toJSONString(map));
        System.out.println(s1);

        Map m = new HashMap();
        m.put("page","http://");
        m.put("template_id","fkdsajlfjk");
        m.put("touser","dfkljskaijf");
        m.put("form_id","jkdfj8923ur022ewro30");
        m.put("keyword1", "******");
        /*****其他参数****/
        
        //发送微信模板消息
        String url2 = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="+accessToken;
        String s2 = UrlUtil.doPost(url2, JSON.toJSONString(m));
        System.out.println(s2);
    }

        获取小程序的二维码的返回类型Content-Type=image/jpeg

        发送消息返回的Content-Type=iapplication/json; encoding=utf-8

 

 

 

 

你可能感兴趣的:(Java小工具)