Android HttpUrlConnection响应为空,以及如何获取响应代码

问题描述 投票:0回答:1

我有此代码,但响应Toast为空谁能告诉我是什么问题?我也不知道如何获得响应代码

谢谢

 register_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                new JSONTask().execute(main_url);


            }
        });





public class JSONTask extends AsyncTask<String,String,String>{

        @Override
        protected String doInBackground(String... params) {
            HttpURLConnection connection=null;
            BufferedReader reader=null;

            try {
                URL url = new URL(params[0]);
                connection=(HttpURLConnection)url.openConnection();
                connection.setRequestMethod("GET");
                int responseCode = connection.getResponseCode();
                connection.connect();

                InputStream is;

                if (responseCode>=200&&responseCode<400){
                    is = connection.getInputStream();
                }else{
                    is = connection.getErrorStream();
                }


                reader = new BufferedReader(new InputStreamReader(is));

                StringBuilder stringBuilder = new StringBuilder();

                String line = "";
                while ((line=reader.readLine()) != null){
                    stringBuilder.append(line);
                }

                return stringBuilder.toString();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if (connection != null){
                    connection.disconnect();
                }

                if (reader != null){
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            return null;
        }
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            Toast.makeText(getApplicationContext(),result,Toast.LENGTH_SHORT).show();
        }
    }
java android httpurlconnection
1个回答
0
投票

您的connection.connect();用getresponsecode方法完成连接是没有用的。此外,检查您的responseCode的值(如果它小于200,您将获得NullPointerException)


0
投票
 @Override
 protected String doInBackground(String... params) {
     return null; //Remove this line and replace with below
     return stringBuilder.toString();
}
© www.soinside.com 2019 - 2024. All rights reserved.