1. 程式人生 > >呼叫企業微信應用推送api推送訊息(spingboot)

呼叫企業微信應用推送api推送訊息(spingboot)

    //推送訊息
    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出發前可檢視<a href=\"http://work.weixin.qq.com\">郵件中心視訊實況</a>,聰明避開排隊。";

        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; }

傳送的是文字訊息,打印出來微信返回的資訊:

 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<String, String> 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<String, String> 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<String, String> Stringparams,Map<String, Long> 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<String, String> 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<String, String> 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<String, String> headerMap, Map<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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;
   }
}