HttpURLConnetionDemo

来源:互联网 发布:网络现在做什么挣钱 编辑:程序博客网 时间:2024/06/09 14:59


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public void btnForGet(View view){

        new Thread(){

            @Override
            public void run() {

                getHealthForGet();

            }
        }.start();



    }

    public void btnForPost(View view){


        new Thread(){
            @Override
            public void run() {

                getHealthForPost();

            }
        }.start();


    }


    /**
     * 使用HttpURLConnection请求数据
     * 请求方式 : POST
     */
    private void getHealthForPost(){


        try {
            URL url = new URL("http://japi.juhe.cn/health_knowledge/categoryList");

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);


            //设置请求参数
            OutputStream os = connection.getOutputStream();
            os.write(("key=eb033dfcf95c03f9f451f6973049e6be").getBytes());
            //将请求参数刷到服务器端
            os.flush();

            //服务器响应
            int code = connection.getResponseCode();
            if(code == 200){
                //得到服务器响应内容
                InputStream is = connection.getInputStream();
                String info = StreamTools.readFromNetWork(is);
                System.out.println("结果 : "+info);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }





    /**
     * 使用HttpURLConnection获取数据
     * API
     * 请求方式 : get
     */
    private void getHealthForGet(){


        try {
            //创建URL
            URL url = new URL("http://japi.juhe.cn/health_knowledge/categoryList?key=eb033dfcf95c03f9f451f6973049e6be");
            //敲回车
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //设置常用的属性
            //设置请求方式
            connection.setRequestMethod("GET");
            //设置连接服务器的时间
            connection.setConnectTimeout(5 * 1000);
            //设置读取网络数据的时间
            connection.setReadTimeout(5 * 1000);


            //等待服务器响应
            int code = connection.getResponseCode();

            if(code == 200){//判断服务器是否响应成功

                InputStream is = connection.getInputStream();

                String info = StreamTools.readFromNetWork(is);

                System.out.println("结果 : "+info);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }












}