Android HttpUrlConnection简单的网站连接

时间:2016-02-25 09:21:10

标签: android

我想检查我的apache-server中的本地网站是否已启动且可访问。 如果通过关于HttpUrlconnection的无数线程阅读并提出以下代码。显示Internet Persmission已设置。该网站目前正在运行,我可以通过我的智能手机webbrowser访问它。我也读过有关输入和输出流的信息,我是否需要它来完成我的任务?

public class MainActivity extends AppCompatActivity {

    boolean value;

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

        state(value);
    }

    public boolean state(boolean value){
        try {
            URL url = new URL("http://192.168.178.59:8090/");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("HEAD");
            httpURLConnection.setConnectTimeout(3000);
            httpURLConnection.setReadTimeout(3000);
            value = true;
            Toast.makeText(MainActivity.this,"true",Toast.LENGTH_SHORT).show();
            return value;
        } catch (MalformedURLException e) {
            e.printStackTrace();
            value = false;
            Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
            return value;
        } catch (IOException e) {
            e.printStackTrace();
            value = false;
            Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
            return value;
        }
    }
}

编辑:来自例外的解决方案

import java.net.HttpURLConnection;

import android.os.AsyncTask;

public class MainActivity extends AppCompatActivity {

    boolean value;

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

    }

    private class HttpTask extends AsyncTask<Boolean, Void, Boolean>
    {

        @Override
        protected Boolean doInBackground(Boolean... params) {
            // TODO Auto-generated method stub
            boolean value=params[0];
            try {
                URL url = new URL("http://192.168.178.59:8090/");
                HttpURLConnection httpURLConnection = (HttpURLConnection)     url.openConnection();
                httpURLConnection.setRequestMethod("HEAD");
                httpURLConnection.setConnectTimeout(3000);
                httpURLConnection.setReadTimeout(3000);
                httpURLConnection.connect();
                value = true;
            //Toast.makeText(MainActivity.this,"true",Toast.LENGTH_SHORT).show();
                return value;
            } catch (MalformedURLException e) {
                e.printStackTrace();
                value = false;
            //Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
                return value;
            } catch (IOException e) {
                e.printStackTrace();
                value = false;
            //Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
                return value;
            }

    }

         @Override
         protected void onPostExecute(Boolean  result) {
             if(result){
               Toast.makeText(MainActivity.this,"true",Toast.LENGTH_SHORT).show(); 
             }
             else{
             Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
             }
         }

    }

}

编辑:服务解决方案

    @Override
            protected void onPostExecute(Boolean  result) {
                if(result){
                    Toast.makeText(NotifiyService.this,"true",Toast.LENGTH_SHORT).show();
                    //Notification in Status Bar
                    NotificationCompat.Builder builder = new NotificationCompat.Builder(NotifiyService.this);
                    builder.setSmallIcon(R.drawable.dummy);
                    Intent intent = new Intent(NotifiyService.this, Main22Activity.class);
                    intent.setAction(Intent.ACTION_MAIN);
                    intent.addCategory(Intent.CATEGORY_LAUNCHER);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    PendingIntent pendingIntent = PendingIntent.getActivity(NotifiyService.this,0,intent,0);
                    builder.setContentIntent(pendingIntent);
                    builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.dummy));
                    builder.setContentTitle(getResources().getString(R.string.newNotify));
                    builder.setContentText(getResources().getString(R.string.newNotify2));
                    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                    notificationManager.notify(1,builder.build());

                }
                else{
                    Toast.makeText(NotifiyService.this,"false",Toast.LENGTH_SHORT).show();
                }

2 个答案:

答案 0 :(得分:1)

只需运行此代码: -

  public boolean state(boolean value){
            URL url;
            String response = "";
            try {
                url = new URL("http://192.168.178.59:8090/");

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(15000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);


                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                //writer.write(getPostDataString(postDataParams));
                writer.write(value);

                writer.flush();
                writer.close();
                os.close();
                int responseCode = conn.getResponseCode();

                if (responseCode == HttpsURLConnection.HTTP_OK) {
                    String line;
                    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    while ((line = br.readLine()) != null) {
                        response += line;
                        System.out.println(response);
                    }
                } else {
                    response = "";

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

答案 1 :(得分:1)

用下面给出的代码替换你的代码。

import java.net.HttpURLConnection;

import android.os.AsyncTask;

public class MainActivity extends AppCompatActivity {

    boolean value;

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

    }

    private class HttpTask extends AsyncTask<Boolean, Void, Boolean>
    {

        @Override
        protected Boolean doInBackground(Boolean... params) {
            // TODO Auto-generated method stub
            boolean value=params[0];
            try {
                URL url = new URL("http://192.168.178.59:8090/");
                HttpURLConnection httpURLConnection = (HttpURLConnection)     url.openConnection();
                httpURLConnection.setRequestMethod("HEAD");
                httpURLConnection.setConnectTimeout(3000);
                httpURLConnection.setReadTimeout(3000);
                httpURLConnection.connect();
                value = true;
            //Toast.makeText(MainActivity.this,"true",Toast.LENGTH_SHORT).show();
                return value;
            } catch (MalformedURLException e) {
                e.printStackTrace();
                value = false;
            //Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
                return value;
            } catch (IOException e) {
                e.printStackTrace();
                value = false;
            //Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
                return value;
            }

    }

         @Override
         protected void onPostExecute(Boolean  result) {
             if(result){
               Toast.makeText(MainActivity.this,"true",Toast.LENGTH_SHORT).show(); 
             }
             else{
             Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
             }
         }

    }

}

修改

要在通知点击上启动新活动,请在Intent intent = new Intent(NotifiyService.this, Main22Activity.class);之后添加以下这些行:

intent .setAction(Intent.ACTION_MAIN);
intent .addCategory(Intent.CATEGORY_LAUNCHER);
intent .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);