来源:http://blog.csdn.net/sxmfendou/article/details/53432390
- public static String sendPost(String url, String param) {
- PrintWriter out = null;
- BufferedReader in = null;
- String result = "";
- try {
- URL realUrl = new URL(url);
-
- URLConnection conn = realUrl.openConnection();
-
- conn.setRequestProperty("user-agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0)");
-
- conn.setDoOutput(true);
- conn.setDoInput(true);
-
- OutputStreamWriter outWriter = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
- out = new PrintWriter(outWriter);
-
- out.print(param);
-
- out.flush();
-
- in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
- String line;
- while ((line = in.readLine()) != null) {
- in = new BufferedReader(new InputStreamReader(conn.getInputStream()));result += line;
- }
- } catch (Exception e) {
- System.out.println("发送 POST 请求出现异常!"+e);
- e.printStackTrace();
- }
-
- finally{
- try{
- if(out!=null){
- out.close();
- }
- if(in!=null){
- in.close();
- }
- }
- catch(IOException ex){
- ex.printStackTrace();
- }
- }
- return result;
- }
- public static void sendTextMessageToUser(HttpServletRequest request,String content,String toUser){
- String json = "{\"touser\": \""+toUser+"\",\"msgtype\": \"text\", \"text\": {\"content\": \""+content+"\"}}";
-
-
- String accessToken = getAccessToken(request);
-
-
- String action = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+accessToken;
-
- System.out.println("json:"+json);
- try {
- String result = HttpJsonUtil.sendPost(action, json);
- System.out.println(result);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }

我自己都不知道在这个地方倒下了多少次了:
关键代码:
// 获取URLConnection对象对应的输出流
OutputStreamWriter outWriter = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
out = new PrintWriter(outWriter);
乱码时候的写法是:
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
java微信 客服接口-发消息 中文乱码
原文:http://www.cnblogs.com/zouhao/p/6900694.html