Android HttpURLConnection GET POST

    private void httpRequest(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection httpURLConnection=null;
                BufferedReader bufferedReader=null;
                try {
                    URL url=new URL("http://www.baidu.com");
                    httpURLConnection = (HttpURLConnection)url.openConnection();
                    httpURLConnection.setRequestMethod("GET");
                    httpURLConnection.setReadTimeout(8000);
                    httpURLConnection.setConnectTimeout(8000);
                    InputStream inputStream=httpURLConnection.getInputStream();
                    bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
                    StringBuilder stringBuilder=new StringBuilder();
                    String line="";
                    while ((line=bufferedReader.readLine())!=null){
                        stringBuilder.append(line);
                    }
                    showResponse(stringBuilder.toString());
                    //下面是POST模式
                    //httpURLConnection.setRequestMethod("POST");
                    //DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());
                    //out.writeBytes("user=admin&password=123456");
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    if(httpURLConnection!=null){
                        httpURLConnection.disconnect();
                    }
                    if(bufferedReader!=null){
                        try {
                            bufferedReader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();

    }

    private void showResponse(final String outputString){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                responseText.setText(outputString);
            }
        });
    }
发布了10 篇原创文章 · 获赞 0 · 访问量 275

猜你喜欢

转载自blog.csdn.net/yixin8/article/details/104209432