/**
* 发送客服消息给单一用户
* @param openId 用户唯一标示
* @param message 发送给用户的消息
*/
public void senMessageToSingleUser(String openId, String message, String accessToken) {
String action = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + accessToken;
try {
WXMessage wxMessage = new WXMessage();
wxMessage.setMsgtype("text");
wxMessage.setTouser(openId);
WXMessageText text = new WXMessageText();
text.setContent(message);
wxMessage.setText(text);
Gson gson = new Gson();
String msg = gson.toJson(wxMessage);
URL url = new URL(action);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
http.connect();
OutputStream os = http.getOutputStream();
os.write(msg.getBytes("UTF-8"));// 传入参数
os.flush();
os.close();
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String message1 = new String(jsonBytes, "UTF-8");
System.out.println(message1);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String sendPost(String url, String content, String accessToken) throws IOException {
String action = url + "?access_token=" + accessToken;
URL _url = new URL(action);
HttpURLConnection http = (HttpURLConnection) _url.openConnection();
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
http.connect();
OutputStream os = http.getOutputStream();
os.write(content.getBytes("UTF-8"));// 传入参数
os.flush();
os.close();
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String message1 = new String(jsonBytes, "UTF-8");
return message1;
}
/**
* 微信客服消息实体类
* @author Draven
* @date 2016年9月28日
* @e-mail draven1122@163.com
*/
public class WXMessage {
private String touser;
private String msgtype;
private WXMessageText text;
public String getTouser() {
return touser;
}
public void setTouser(String touser) {
this.touser = touser;
}
public String getMsgtype() {
return msgtype;
}
public void setMsgtype(String msgtype) {
this.msgtype = msgtype;
}
public WXMessageText getText() {
return text;
}
public void setText(WXMessageText text) {
this.text = text;
}
}
这里需要gson.jar进行对象与json的转换