试图通过HttpURLConnection了解我尝试连接的网站是否有效

时间:2016-01-11 18:20:45

标签: java android httpresponse httpurlconnection

我正在开发一个连接到网站并从中获取数据的应用程序。我遇到的问题是,当我尝试检查网站是否有效时,有时它会在我的应用程序中显示其离线状态,但当我在浏览器上尝试使用相同的网站时,它正在工作。我已经尝试 HttpURLConnection 检查响应时间,如果它等于 200 返回 true ,但大多数情况下它没有 work.It表明网站不在线。我使用线程给asynctask一些延迟,但仍然不能完美。

这是代码。

package com.bu.innovate.bustudentportal;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.pnikosis.materialishprogress.ProgressWheel;

import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

public class Splash_Activity extends Activity implements Animation.AnimationListener {

    UserSessionManager session;
    Data data;
    ProgressWheel progress;

    boolean check;
    String url = "";

    FileInputStream inputStream;
    String filename = "newMyProfileData";
    Animation animFadein;
    Animation animFadeout;
    LinearLayout linearLayout;

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        boolean finish = getIntent().getBooleanExtra("finish", false);
        if (finish) {

            finish();
            return;
        }
        setContentView(R.layout.splast_activty);


        linearLayout = (LinearLayout) findViewById(R.id.splash);

        progress = (ProgressWheel) findViewById(R.id.progressbar);

        session = new UserSessionManager(getApplicationContext());
        HashMap<String, String> user = session.getUserDetails();

        url = user.get(UserSessionManager.KEY_URL);

        animFadein = AnimationUtils.loadAnimation(this,
                R.anim.blink);
        animFadeout = AnimationUtils.loadAnimation(this,
                R.anim.fade_out);
        animFadein.setAnimationListener(this);
        animFadeout.setAnimationListener(this);

        animFadein.setDuration(1300);
        animFadeout.setDuration(1000);
        animFadeout.setStartOffset(1200 + animFadein.getStartOffset() + 1200);


        data = new Data(getApplicationContext());

        progress.spin();

        if(animFadein!=null)
        {
            linearLayout.startAnimation(animFadein);

        }

        if (!session.checkLogin() && isOnline()) {

            final Handler handler2 = new Handler();
            handler2.postDelayed(new Runnable() {
                @Override
                public void run() {
                    new checkingnetwork().execute();
                }
            }, 2000);


            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    getcheck();
                }
            }, 5000);
        }
        else if (!session.checkLogin() && !isOnline()) {

            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    getcheck();
                }
            }, 4000);

        } else {
            getcheck();
        }
    }


    public void getcheck() {

        if (!data.isOnline() && !session.checkLogin()) {
            MyProfile_Data data_file;
            new MyProfile_Data();

            try {
                File filew = new File(Splash_Activity.this.getCacheDir(), filename);
                inputStream = new FileInputStream(filew);

                ObjectInputStream input = new ObjectInputStream(inputStream);
                data_file = (MyProfile_Data) input.readObject();

                Data.name_person = data_file.getName();
                Data.name_enroll = data_file.getEnrollment();

            } catch (Exception e) {
                e.printStackTrace();
            }
            Intent myIntent = new Intent(getBaseContext(), Navigation_drawer.class);
            startActivityForResult(myIntent, 0);


        } else if (isOnline()) {

            if (check && !session.checkLogin()) {
                Data.checkwebsite = check;
                new Login_Activity_Again(Splash_Activity.this).execute();
            } else if (!session.checkLogin() && !check) {

                MyProfile_Data data_file;
                new MyProfile_Data();

                try {
                    File filew = new File(Splash_Activity.this.getCacheDir(), filename);
                    inputStream = new FileInputStream(filew);

                    ObjectInputStream input = new ObjectInputStream(inputStream);
                    data_file = (MyProfile_Data) input.readObject();

                    Data.name_person = data_file.getName();
                    Data.name_enroll = data_file.getEnrollment();

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

                Toast.makeText(getApplicationContext(), "Cannot connect to the webserver.Going into offline mode",
                        Toast.LENGTH_LONG).show();
                Data.w_check = 1;

                Intent myIntent = new Intent(getBaseContext(), Navigation_drawer.class);
                startActivityForResult(myIntent, 0);

            }
        } else {
            if (session.checkLogin())
                finish();

        }
    }


    public boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        //should check null because in air plan mode it will be null
        return (netInfo != null && netInfo.isConnected());
    }

    @Override
    public void onAnimationStart(Animation animation) {

       // linearLayout.startAnimation(animFadein);
    }

    @Override
    public void onAnimationEnd(Animation animation) {


    }

    @Override
    public void onAnimationRepeat(Animation animation) {

    }


    public class checkingnetwork extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            try {

                // FIRST METHOD I TRIED
                HttpURLConnection urlc = (HttpURLConnection) (new URL(url).openConnection());
                urlc.setRequestProperty("User-Agent", "Test");
                urlc.setRequestProperty("Connection", "close");
                urlc.setConnectTimeout(3000);
                urlc.connect();
                check = (urlc.getResponseCode() == 200);

                // SECOND METHOD I TRIED
                HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                connection.setConnectTimeout(5000);
                connection.setReadTimeout(5000);
                connection.setRequestMethod("HEAD");
                int responseCode = connection.getResponseCode();
                check =  (200 <= responseCode && responseCode <= 399);

                System.out.print(responseCode);

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

            return null;

        }
    }

}

logcat就在这里..

  1-11 23:04:24.804 10320-10638/com.bu.innovate.bustudentportal I/System.out: (HTTPLog)-Static: SBServiceAPI: getService class android.os.ServiceManager
01-11 23:04:24.804 10320-10638/com.bu.innovate.bustudentportal I/System.out: (HTTPLog)-Static: isShipBuild true
01-11 23:04:24.804 10320-10638/com.bu.innovate.bustudentportal I/System.out: (HTTPLog)-Thread-18855-353874012: SmartBonding Enabling is true, SHIP_BUILD is true, log to file is false, DBG is false
01-11 23:04:26.204 10320-10320/com.bu.innovate.bustudentportal D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN
01-11 23:04:27.824 10320-10320/com.bu.innovate.bustudentportal I/Timeline: Timeline: Activity_launch_request id:com.bu.innovate.bustudentportal time:27606813
01-11 23:04:27.984 10320-10320/com.bu.innovate.bustudentportal D/debug: Screen inches : 5.2007338145504045
01-11 23:04:27.994 10320-10320/com.bu.innovate.bustudentportal V/BitmapFactory: DecodeImagePath(decodeResourceStream3) : res/drawable-xxhdpi-v4/abc_ic_ab_back_mtrl_am_alpha.png
01-11 23:04:28.024 10320-10320/com.bu.innovate.bustudentportal V/BitmapFactory: DecodeImagePath(decodeResourceStream3) : res/drawable/header.jpg
01-11 23:04:28.114 10320-10320/com.bu.innovate.bustudentportal V/BitmapFactory: DecodeImagePath(decodeResourceStream3) : res/drawable-xxhdpi-v4/profile_picture.png
01-11 23:04:28.204 10320-10320/com.bu.innovate.bustudentportal D/Activity: performCreate Call secproduct feature valuefalse
01-11 23:04:28.204 10320-10320/com.bu.innovate.bustudentportal D/Activity: performCreate Call debug elastic valuetrue
01-11 23:04:28.234 10320-10320/com.bu.innovate.bustudentportal V/BitmapFactory: DecodeImagePath(decodeResourceStream3) : res/drawable-xxhdpi-v4/tick_logo.png
01-11 23:04:28.234 10320-10320/com.bu.innovate.bustudentportal V/BitmapFactory: DecodeImagePath(decodeResourceStream3) : res/drawable-xxhdpi-v4/time_logo.png
01-11 23:04:28.234 10320-10320/com.bu.innovate.bustudentportal V/BitmapFactory: DecodeImagePath(decodeResourceStream3) : res/drawable-xxhdpi-v4/result_logo.png
01-11 23:04:28.274 10320-10320/com.bu.innovate.bustudentportal D/AbsListView: Get MotionRecognitionManager
01-11 23:04:28.294 10320-10320/com.bu.innovate.bustudentportal D/AbsListView: Get MotionRecognitionManager
01-11 23:04:28.324 10320-10320/com.bu.innovate.bustudentportal D/AbsListView: Get MotionRecognitionManager
01-11 23:04:28.334 10320-10320/com.bu.innovate.bustudentportal D/AbsListView: Get MotionRecognitionManager
01-11 23:04:28.484 10320-10320/com.bu.innovate.bustudentportal V/BitmapFactory: DecodeImagePath(decodeResourceStream3) : res/drawable-xxhdpi-v4/profile_logo.png
01-11 23:04:28.484 10320-10320/com.bu.innovate.bustudentportal V/BitmapFactory: DecodeImagePath(decodeResourceStream3) : res/drawable-xxhdpi-v4/progress_logo.png
01-11 23:04:28.484 10320-10320/com.bu.innovate.bustudentportal V/BitmapFactory: DecodeImagePath(decodeResourceStream3) : res/drawable-xxhdpi-v4/notification_logo.png
01-11 23:04:28.494 10320-10320/com.bu.innovate.bustudentportal V/BitmapFactory: DecodeImagePath(decodeResourceStream3) : res/drawable-xxhdpi-v4/eva.png
01-11 23:04:28.494 10320-10320/com.bu.innovate.bustudentportal V/BitmapFactory: DecodeImagePath(decodeResourceStream3) : res/drawable-xxhdpi-v4/password_logo.png
01-11 23:04:28.504 10320-10320/com.bu.innovate.bustudentportal V/BitmapFactory: DecodeImagePath(decodeResourceStream3) : res/drawable-xxhdpi-v4/feedback_logo.png
01-11 23:04:28.514 10320-10320/com.bu.innovate.bustudentportal V/BitmapFactory: DecodeImagePath(decodeResourceStream3) : res/drawable-xxhdpi-v4/privacy_logo.png
01-11 23:04:28.524 10320-10320/com.bu.innovate.bustudentportal W/View: requestLayout() improperly called by android.support.v7.widget.AppCompatImageView{3bfd695e V.ED.... ......ID 0,0-0,0 #7f0d01ad app:id/selector} during layout: running second layout pass
01-11 23:04:28.524 10320-10320/com.bu.innovate.bustudentportal W/View: requestLayout() improperly called by android.support.v7.widget.AppCompatImageView{1db4b13f V.ED.... ......I. 0,0-0,0 #7f0d01ad app:id/selector} during layout: running second layout pass
01-11 23:04:28.524 10320-10320/com.bu.innovate.bustudentportal W/View: requestLayout() improperly called by android.support.v7.widget.AppCompatImageView{9aada0c V.ED.... ......I. 0,0-0,0 #7f0d01ad app:id/selector} during layout: running second layout pass
01-11 23:04:28.644 10320-10320/com.bu.innovate.bustudentportal I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@12a519a2 time:27607635
01-11 23:04:28.644 10320-10320/com.bu.innovate.bustudentportal I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@29c55571 time:27607635
01-11 23:04:30.024 10320-10638/com.bu.innovate.bustudentportal W/System.err: java.net.SocketTimeoutException
01-11 23:04:30.044 10320-10638/com.bu.innovate.bustudentportal W/System.err:     at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
01-11 23:04:30.044 10320-10638/com.bu.innovate.bustudentportal W/System.err:     at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:37)
01-11 23:04:30.044 10320-10638/com.bu.innovate.bustudentportal W/System.err:     at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:237)
01-11 23:04:30.044 10320-10638/com.bu.innovate.bustudentportal W/System.err:     at com.android.okio.Okio$2.read(Okio.java:116)
01-11 23:04:30.044 10320-10638/com.bu.innovate.bustudentportal W/System.err:     at com.android.okio.RealBufferedSource.indexOf(RealBufferedSource.java:150)
01-11 23:04:30.044 10320-10638/com.bu.innovate.bustudentportal W/System.err:     at com.android.okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:97)
01-11 23:04:30.044 10320-10638/com.bu.innovate.bustudentportal W/System.err:     at com.android.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:198)
01-11 23:04:30.044 10320-10638/com.bu.innovate.bustudentportal W/System.err:     at com.android.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:119)
01-11 23:04:30.044 10320-10638/com.bu.innovate.bustudentportal W/System.err:     at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:777)
01-11 23:04:30.044 10320-10638/com.bu.innovate.bustudentportal W/System.err:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:379)
01-11 23:04:30.044 10320-10638/com.bu.innovate.bustudentportal W/System.err:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:323)
01-11 23:04:30.044 10320-10638/com.bu.innovate.bustudentportal W/System.err:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:491)
01-11 23:04:30.044 10320-10638/com.bu.innovate.bustudentportal W/System.err:     at com.bu.innovate.bustudentportal.Splash_Activity$checkingnetwork.doInBackground(Splash_Activity.java:223)
01-11 23:04:30.044 10320-10638/com.bu.innovate.bustudentportal W/System.err:     at com.bu.innovate.bustudentportal.Splash_Activity$checkingnetwork.doInBackground(Splash_Activity.java:208)
01-11 23:04:30.044 10320-10638/com.bu.innovate.bustudentportal W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:288)
01-11 23:04:30.044 10320-10638/com.bu.innovate.bustudentportal W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
01-11 23:04:30.044 10320-10638/com.bu.innovate.bustudentportal W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
01-11 23:04:30.044 10320-10638/com.bu.innovate.bustudentportal W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
01-11 23:04:30.044 10320-10638/com.bu.innovate.bustudentportal W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
01-11 23:04:30.044 10320-10638/com.bu.innovate.bustudentportal W/System.err:     at java.lang.Thread.run(Thread.java:818)
01-11 23:05:00.344 10320-10351/com.bu.innovate.bustudentportal I/art: Debugger is no longer active
01-11 23:05:00.644 10320-10320/com.bu.innovate.bustudentportal D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN
01-11 23:06:03.744 10320-10320/com.bu.innovate.bustudentportal I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@12a519a2 time:27702733

我试图修复它,并使用两种方法来解决这个问题,但是有时甚至没有什么加上网络速度很慢时它也没有连接。如果你们帮我解决这个问题,那将非常有帮助。

0 个答案:

没有答案