调用企业微信应用推送api推送消息(spingboot)

调用企业微信应用推送api推送消息(spingboot)_第1张图片

    //推送消息
    public static String sendMessage(){
        //String token =getAccessToken();
        String token ="6qK5a5k07UXGDt6jt5KAmn5jhaU-GferPBWUdalHafRXGWpBHTtpJIBSR-LgnaiPpNKBAruhEUPhyMdemC7TyyzWgf2bb5vCze-b-fN3JogpPvIAz30mnVUj1Roo6Wxv78_JXB0Ii3OU8PmoInYOA8Q91Pl_UKqHoZV0KCFdZExtb84KFdNavoQGkRZXZzbRZZneZxLQOgxgvP0QT51PYA";
        String userId="107944";//推送给具体某个人的userid
        String departmentId="";
        //String msgtype="mytext";
        String agentid=WxConstants.AGENTID;//WxConstants.AGENTID是应用的agenid
        String content="测试消息推送:你的快递已到,请携带工卡前往邮件中心领取。\n出发前可查看邮件中心视频实况,聪明避开排队。";

        JSONObject params = new JSONObject();
        params.put("touser", userId);
//        params.put("toparty", departmentId);
        params.put("agentid", agentid);
        JSONObject mytext = new JSONObject();
        mytext.put("content",content);
        params.put("msgtype", "text");
        params.put("text",mytext);

        try {
            String aa=HttpUtils.httpPostMethod(WxConstants.POST_SEND_MESSAGE_UR + "?access_token=" + token, new HashMap<>(), params.toJSONString());
            log.info("1.推送消息请求微信接口=="+aa);
            log.info("2.推送消息请求微信接口=="+JSON.toJSONString(aa));
            return aa;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

调用企业微信应用推送api推送消息(spingboot)_第2张图片

发送的是文本消息,打印出来微信返回的信息:

 1.推送消息请求微信接口=={"errcode":0,"errmsg":"ok","invaliduser":""}

2.推送消息请求微信接口=="{\"errcode\":0,\"errmsg\":\"ok\",\"invaliduser\":\"\"}"

WxConstants是自己定义的常量类,里面是微信的url

联网请求类:HttpUtils

import okhttp3.*;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URLEncoder;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class HttpUtils {

   public static String httpGetMethod(String url, Map params)
         throws IOException {
      OkHttpClient client = new OkHttpClient();
      StringBuffer paramStr = new StringBuffer();
      paramStr.append("?");
      params.keySet().stream().forEach(key -> {
         paramStr.append(key + "=" + params.get(key) + "&");
      });
      paramStr.setLength(paramStr.length() - 1);
      Request request = new Request.Builder().url(url + paramStr.toString())
            .get().build();
      Response response = client.newCall(request).execute();
      return response.body().string();
   }

   public static String httpPostParams(String url, Map params)
         throws IOException {
      OkHttpClient client = new OkHttpClient();
      StringBuffer paramStr = new StringBuffer();
      paramStr.append("?");
      params.keySet().stream().forEach(key -> {
         paramStr.append(key + "=" + params.get(key) + "&");
      });
      paramStr.setLength(paramStr.length() - 1);
      System.out.println("测试:" + url + paramStr.toString());

      Request request = new Request.Builder().url(url + paramStr.toString())
            .post(okhttp3.internal.Util.EMPTY_REQUEST).build();
      Response response = client.newCall(request).execute();
      return response.body().string();
   }

   public static String httpPostStringParamsAndlongParams(String url, Map Stringparams,Map Longparams)
         throws IOException {
      OkHttpClient client = new OkHttpClient();
      StringBuffer paramStr = new StringBuffer();
      paramStr.append("?");
      Stringparams.keySet().stream().forEach(key -> {
         paramStr.append(key + "=" + Stringparams.get(key) + "&");
      });
      Longparams.keySet().stream().forEach(key -> {
         paramStr.append(key + "=" + Stringparams.get(key) + "&");
      });
      paramStr.setLength(paramStr.length() - 1);
      System.out.println("测试:" + url + paramStr.toString());

      Request request = new Request.Builder().url(url + paramStr.toString())
            .post(okhttp3.internal.Util.EMPTY_REQUEST).build();
      Response response = client.newCall(request).execute();
      return response.body().string();
   }

   public static String httpPostMethod(String url, Map params)
         throws IOException {
      OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(60, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS).build();
      FormBody.Builder formBody = new FormBody.Builder();
      params.keySet().stream().forEach(key -> {
         formBody.add(key, params.get(key));
      });
      Request request = new Request.Builder().url(url).post(formBody.build())
            .build();
      Response response = client.newCall(request).execute();
      return response.body().string();
   }

   public static String httpPostMethodWithUtf8(String url,
         Map params) throws IOException {
      OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(60, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS).build();
      FormBody.Builder formBody = new FormBody.Builder();
      params.keySet().stream().forEach(key -> {
         try {
            formBody.add(key, URLEncoder.encode(params.get(key), "UTF-8"));
         } catch (Exception e) {
            e.printStackTrace();
         }
      });
      Request request = new Request.Builder().url(url).post(formBody.build())
            .build();
      Response response = client.newCall(request).execute();
      return response.body().string();
   }

   public static String httpPostMethod(String url,
         Map headerMap, Map params)
         throws IOException {
      OkHttpClient client = new OkHttpClient();
      FormBody.Builder formBody = new FormBody.Builder();
      Headers headers = Headers.of(headerMap);
      params.keySet().stream().forEach(key -> {
         formBody.add(key, params.get(key));
      });
      Request request = new Request.Builder().url(url).headers(headers)
            .post(formBody.build()).build();
      Response response = client.newCall(request).execute();
      return response.body().string();
   }


   public static Response httpPostResponse(String url, Map headers,
                              String requestBodys) throws IOException {
      OkHttpClient client = new OkHttpClient();
      MediaType mediaType = MediaType
            .parse(headers.get("Content-Type") == null ? "application/json"
                  : headers.get("Content-Type"));
      RequestBody requestBody = RequestBody.create(mediaType, requestBodys);
      Headers headerMap = okhttp3.Headers.of(headers);
      Request request = new Request.Builder().url(url).headers(headerMap)
            .post(requestBody).build();
      Response response = client.newCall(request).execute();
      return response;
   }



   public static String httpPostMethod(String url, Map headers,
         String requestBodys) throws IOException {
      OkHttpClient client = new OkHttpClient();
      MediaType mediaType = MediaType
            .parse(headers.get("Content-Type") == null ? "application/json"
                  : headers.get("Content-Type"));
      RequestBody requestBody = RequestBody.create(mediaType, requestBodys);
      Headers headerMap = okhttp3.Headers.of(headers);
      Request request = new Request.Builder().url(url).headers(headerMap)
            .post(requestBody).build();
      Response response = client.newCall(request).execute();
      return response.body().string();
   }

   public static String postMethod(String url, Map headers,
         InputStream bodyContent) throws IOException {
      OkHttpClient client = new OkHttpClient();
      MediaType mediaType = MediaType
            .parse(headers.get("Content-Type") == null ? "application/json"
                  : headers.get("Content-Type"));
      int total = (bodyContent.available() / 1024 + 1) * 1024;
      byte b[] = new byte[total];
      byte r[] = new byte[1024];
      int len = 0;
      int temp = 0; // 所有读取的内容都使用temp接收
      while ((temp = bodyContent.read(r)) != -1) { // 当没有读取完时,继续读取
         System.arraycopy(r, 0, b, 1024 * len, 1024);
         len++;
      }
      RequestBody requestBody = RequestBody.create(mediaType, b);
      Headers headerMap = okhttp3.Headers.of(headers);
      Request request = new Request.Builder().url(url).headers(headerMap)
            .post(requestBody).build();
      Response response = client.newCall(request).execute();
      bodyContent.reset();
      return response.body().string();
   }

   public static String clientPostMethod(String url,
         Map headers, InputStream bodyContent)
         throws IOException {

      HttpPost method = new HttpPost(url);
      HttpClient httpClient = new DefaultHttpClient();
      headers.keySet().stream().forEach(head -> {
         method.addHeader(new BasicHeader(head, headers.get(head)));
      });
      if (bodyContent != null) {
         method.setEntity(new InputStreamEntity(bodyContent, -1));
      }
      HttpResponse postResponse = httpClient.execute(method);
      return getResponsBodyAsString(postResponse.getEntity().getContent());
   }

   public static String clientPostMethod(String url,
         Map headers) throws IOException {

      HttpPost method = new HttpPost(url);
      HttpClient httpClient = new DefaultHttpClient();
      headers.keySet().stream().forEach(head -> {
         method.addHeader(new BasicHeader(head, headers.get(head)));
      });
      HttpResponse postResponse = httpClient.execute(method);
      return getResponsBodyAsString(postResponse.getEntity().getContent());
   }

   private static String getResponsBodyAsString(InputStream input)
         throws IOException {
      String responsBodyString = null;
      try {
         Reader reader = new InputStreamReader(input, "utf-8");
         StringBuilder b = new StringBuilder();
         char[] c = new char[1024];
         int len;
         while (0 < (len = reader.read(c))) {
            b.append(c, 0, len);
         }
         responsBodyString = b.toString();
      } finally {
         input.close();
      }
      return responsBodyString;
   }
}

你可能感兴趣的:(spring,boot)