package com.maniu.http;

import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpRequest implements IHttpRequest {
    private String url;
    private byte[] data;
    private JasonCallbackListener jasonCallbackListener;
    HttpURLConnection httpURLConnection;

    @Override
    public void setUrl(String url) {
        this.url = url;
    }

    @Override
    public void setData(byte... data) {
        this.data = data;
    }

    @Override
    public void setListenner(JasonCallbackListener jasonCallbackListener) {
        this.jasonCallbackListener = jasonCallbackListener;
    }

    @Override
    public void excute() {
        //请求服务器的代码
        //写请求服务器的代码
        URL url = null;
        try {
            url = new URL(this.url);
            //给httpURLConnection设置一些相关的参数
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(6000);  //连接超时时间
            httpURLConnection.setUseCaches(false);  //不使用缓存
            httpURLConnection.setInstanceFollowRedirects(true); //是成员变量 仅作用域当前函数，设置当前这个对象
            httpURLConnection.setReadTimeout(3000); //响应超时的时间
            httpURLConnection.setDoInput(true);  //设置这个连接对否可以写入数据;
            httpURLConnection.setDoOutput(true);  //设置这个连接对否可以输出数据;
            httpURLConnection.setRequestMethod("POST");    //设置这个请求的方法
            httpURLConnection.setRequestProperty("Content-Type","application/json;charset=UTF-8");
            httpURLConnection.connect();    //建立连接
            //---------------使用字节流发送数据---------------------------
            OutputStream out = httpURLConnection.getOutputStream();
            //缓冲字节流  包装字节流
            BufferedOutputStream bos = new BufferedOutputStream(out);
            //把字节流数组写入缓冲区中
            bos.write(data);
            //刷新缓冲区 发送数据
            bos.flush();
            out.close();
            bos.close();
            //如果响应码为200代表请求访问成功
            if(httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
                InputStream in = httpURLConnection.getInputStream();
                //回调内部的回调接口
                jasonCallbackListener.onSuccess(in);
            }else{
                throw new RuntimeException("请求失败");
            }
        } catch (Exception e) {
            throw new RuntimeException("请求失败");
        }finally {
            httpURLConnection.disconnect();
        }
    }

    @Override
    public JasonCallbackListener getJasonCallbackListenner() {
        return jasonCallbackListener;
    }


}
