HttpURLConnection 请求腾讯sms 字符流io典型应用

    public static void sendMsg(String nationCode, String phoneNumber, String content) throws IOException, JSONException, NoSuchAlgorithmException, SmsException
    {
        Random random = new Random();
        long rnd = random.nextInt(999999) % (999999 - 100000 + 1) + 100000;
        String wholeUrl = String.format("%s?sdkappid=%d&random=%d", URL, SDKAPPID, rnd);

        java.net.URL object = new URL(wholeUrl);
        HttpURLConnection con = (HttpURLConnection) object.openConnection();
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Accept", "application/json");
        con.setRequestMethod("POST");
        JSONObject data = new JSONObject();
        JSONObject tel = new JSONObject();
        tel.put("nationcode", nationCode);
        String phone = phoneNumber;
        tel.put("phone", phone);
        data.put("type", "0");
        data.put("msg", content);
        String sig = stringMD5(APPKEY.concat(phone));
        data.put("sig", sig);
        data.put("tel", tel);
        OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream(), "utf-8");
        wr.write(data.toString());
        wr.flush();

        // 显示 POST 请求返回的内容
        StringBuilder sb = new StringBuilder();
        int HttpResult = con.getResponseCode();
        if (HttpResult == HttpURLConnection.HTTP_OK)
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
            String line;
            while ((line = br.readLine()) != null)
            {
                sb.append(line + "
");
            }
            br.close();
            JSONObject reObj = new JSONObject(sb.toString());
            String res = (String)reObj.get("result");
            if(!"0".equals(res)) {
                System.out.println("" + sb.toString());
                LOGGER.error("SmsSender::sendMsg" + "-" + phoneNumber + ","+(String)reObj.get("errmsg"));
            } else {

            }


        } else
        {
            LOGGER.error("send failed and rps is: " + con.getResponseMessage());
            throw new SmsException("send failed and rps is: " + con.getResponseMessage());
        }
    }


con.setRequestProperty("Content-Type", "application/json");

按腾讯sms要求,按json组织包体:https://cloud.tencent.com/document/product/382/5808


 OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream(), "utf-8");
        wr.write(data.toString());
        wr.flush();

OutputStreamWriter是OutputStream到Writer转换的桥梁,借助这个桥梁取得参数的字符流形式(utf-8)

注意    Writer 需要 flush 强制清空缓冲区 或 close 关闭流输出缓冲区


BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
            String line;
            while ((line = br.readLine()) != null)
            {
                sb.append(line + "
");
            }


InputStreamReader是一个连接字节流和字符流的桥梁,它将字节流转变为字符流。借助这个桥梁,将返回的InputStream字节流以utf-8的形式转化为字符流,(这里还是用了装饰器BufferedReader)然后读取返回的json字符串


JSONObject reObj = new JSONObject(sb.toString());
            String res = (String)reObj.get("result");
            if(!"0".equals(res)) {
                System.out.println("" + sb.toString());
                LOGGER.error("SmsSender::sendMsg" + "-" + phoneNumber + ","+(String)reObj.get("errmsg"));
            } else {

            }

json字符串转为json对象


核心:

Writer(InputStreamWriter)-char[]-Reader(InputStreamReader)

char[]为中介


参考:http://blog.csdn.net/qq_25184739/article/details/51205186


3.字符输入流Reader


在上面的继承关系图中可以看出:

1.    Reader是所有的输入字符流的父类,它是一个抽象类。

2.    CharReaderStringReader是两种基本的介质流,它们分别从Char数组、String中读取数据。PipedReader是从与其它线程共用的管道中读取数据。

3.    BufferedReader很明显就是一个装饰器,它和其子类负责装饰其它Reader对象。

4.    FilterReader是所有自定义具体装饰流的父类,其子类PushbackReaderReader对象进行装饰,会增加一个行号。

5.    InputStreamReader是一个连接字节流和字符流的桥梁,它将字节流转变为字符流。FileReader可以说是一个达到此功能、常用的工具类,在其源代码中明显使用了将FileInputStream转变为Reader的方法。我们可以从这个类中得到一定的技巧。Reader中各个类的用途和使用方法基本和InputStream中的类使用一致。后面会有ReaderInputStream的对应关系。



主要方法:

     (1) public int read() throws IOException; //读取一个字符,返回值为读取的字符 

     (2) public int read(char cbuf[]) throws IOException; /*读取一系列字符到数组cbuf[]中,返回值为实际读取的字符的数量*/ 
     (3) public abstract int read(char cbuf[],int off,int len) throws IOException; 
/*读取len个字符,从数组cbuf[]的下标off处开始存放,返回值为实际读取的字符数量,该方法必须由子类实现*/ 

 



4.字符输出流Writer


在上面的关系图中可以看出:

1.    Writer是所有的输出字符流的父类,它是一个抽象类。

2.    CharArrayWriterStringWriter是两种基本的介质流,它们分别向Char数组、String中写入数据。PipedWriter是向与其它线程共用的管道中写入数据,

3.    BufferedWriter是一个装饰器为Writer提供缓冲功能。

4.    PrintWriterPrintStream极其类似,功能和使用也非常相似。

5.    OutputStreamWriterOutputStreamWriter转换的桥梁,它的子类FileWriter其实就是一个实现此功能的具体类(具体可以研究一SourceCode)。功能和使用和OutputStream极其类似.


 

主要方法:

(1)  public void write(int c) throws IOException //将整型值c的低16位写入输出流 
(2)  public void write(char cbuf[]) throws IOException //将字符数组cbuf[]写入输出流 
(3)  public abstract void write(char cbuf[],int off,int len) throws IOException //将字符数组cbuf[]中的从索引为off的位置处开始的len个字符写入输出流 
(4)  public void write(String str) throws IOException //将字符串str中的字符写入输出流 
(5)  public void write(String str,int off,int len) throws IOException //将字符串str 中从索引off开始处的len个字符写入输出流 



原文地址:https://www.cnblogs.com/silyvin/p/9106685.html