package com.example.sleep;

import android.os.Handler;
import android.os.Message;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class NetWork {

    //定义方法，用来获取信息
    public void getDream(String keywords, Handler handler) {
        new Thread(new Runnable() //创建新的线程来进行网络请求
        {
            @Override
            public void run() {
                String tianapi_data = "";
                try {
                    URL url = new URL( "https://apis.tianapi.com/dream/index");//创建url对象，指定API接口的地址（https://apis.tianapi.com/dream/index）
                    HttpURLConnection  conn = (HttpURLConnection) url.openConnection();//打开HTTP连接
                    conn.setRequestMethod("POST");//设置请求方式为Post
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);
                    conn.setDoOutput(true);
                    conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
                    OutputStream outputStream = conn.getOutputStream();//获取输出流
                    String content = "key=4e90d7122409e092670d627e2129047d&num=10&word="+keywords;//构建请求参数
                    outputStream.write(content.getBytes());//将请求参数写入输出流
                    outputStream.flush();
                    outputStream.close();//关闭输出流
                    InputStream inputStream = conn.getInputStream();//获取输入流
                    InputStreamReader inputStreamReader = new InputStreamReader (inputStream,"utf-8");
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    StringBuilder tianapi = new StringBuilder();
                    String temp = null;
                    while ( null != (temp = bufferedReader.readLine())){
                        tianapi.append(temp);
                    }
                    tianapi_data = tianapi.toString();
                    inputStream.close();//关闭输入流
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println(tianapi_data);
                Message message = handler.obtainMessage();// 使用Handler将API返回的数据封装到Message对象中，发送给主线程进行处理
                message.obj = tianapi_data;
                handler.sendMessage(message);
            }
        }).start();
    }
}