Android client determines whether the server has enabled HttpHostException solution


Android determines whether the server is open. I have tried many methods but nothing works (if the server is not open, it will be stuck at HttpResponse). Some people say that higher versions of Android programs do not allow access to the network in the main thread (network streams can be read and written in the main thread). for verification. (Correction: It’s not that access is not allowed, but that it is very time-consuming and will cause death (if it is not time-consuming, it will not be suspended); Correct answer: When the user clicks a button, if a time-consuming operation is performed, it will not be handled well. It will cause the system to freeze and the user experience is very poor. Android goes one step further. If any activity does not respond for more than 5 seconds, it will be forcibly closed. Therefore, we need to start another thread to handle long-time operations, while the main thread Not affected by it, after the time-consuming operation is completed, the message is sent to the main thread, and the main thread performs corresponding processing. Then the message passing and asynchronous processing between threads use Handler. )


method one:

Add in the onCreate() method of xxxActivity

[java]  view plain   copy
  View code snippets on CODE Derived into my code piece
  1. StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();  
  2. StrictMode.setThreadPolicy(policy);  

These two lines of code were originally added to the Activity I wrote. This method did not solve my problem. Go on...


solution 2:

[java]  view plain   copy
  View code snippets on CODE Derived into my code piece
  1. package  siat.hpc.ngb.utils;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import org.apache.http.HttpResponse;  
  6. import org.apache.http.client.ClientProtocolException;  
  7. import org.apache.http.client.HttpClient;  
  8. import org.apache.http.client.methods.HttpGet;  
  9. import org.apache.http.impl.client.DefaultHttpClient;  
  10. import org.apache.http.params.BasicHttpParams;  
  11. import org.apache.http.params.HttpConnectionParams;  
  12. import org.apache.http.params.HttpParams;  
  13.   
  14. import android.os.AsyncTask;  
  15. import android.util.Log;  
  16.   
  17. public class ConnServer extends AsyncTask<String,String,String>{  
  18.       
  19.     /** 
  20.      *  
  21.      * Determine whether the server is open 
  22.      * @param path network server address 
  23.      * @return  
  24.      * Server starts 
  25.      * The server is not started 
  26.      */  
  27.       
  28.     @Override  
  29.     protected String doInBackground(String... params) {  
  30.         // TODO Auto-generated method stub  
  31.           
  32.           
  33.         try {  
  34.             HttpGet get = new HttpGet(params[0]);  
  35. Log.i("doInBack1...",params[0]);  
  36.             HttpResponse response = new DefaultHttpClient().execute(get);  
  37.               
  38. Log.i("doInBack2...",params[0]);  
  39.             if(response.getStatusLine().getStatusCode() == 200){  
  40.                 return "success";  
  41.             }   
  42.         } catch (ClientProtocolException e) {  
  43.             // TODO Auto-generated catch block  
  44.             e.printStackTrace();  
  45.             return "ClientError";  
  46.         } catch (IOException e) {  
  47.             // TODO Auto-generated catch block  
  48.             e.printStackTrace();  
  49.             return "ServerError";  
  50.         }  
  51.         return "success";  
  52.     }  
  53. }  

Call directly where needed:

The following direct call cannot obtain the return value of the String type. It returns an Object object. For the specific acquisition method, please refer to:

Android has two ways to get the return value of AsyncTask.  This article

[java]  view plain   copy
  View code snippets on CODE Derived into my code piece
  1. if(new ConnServer().execute(AppConstant.BASE_URL).equals("success")){   
[java]  view plain   copy
  View code snippets on CODE Derived into my code piece
  1. 。。。<pre name="code" class="java" style="font-size: 18px;">。。AppConstant.BASE_URL是一个http的字符串:如http://172.21.6.233:8080/  

 
  
[java]  view plain   copy
  View code snippets on CODE Derived into my code piece
  1. }  
方法三:
采用Http方式:

复制代码
public boolean isConnByHttp(){
        boolean isConn = false;
        URL url;
        HttpURLConnection conn = null;
        try {
            url = new URL("ttp://wl.daishu001.com/YHDriver.asmx");
            conn = (HttpURLConnection)url.openConnection();
            conn.setConnectTimeout(1000*5);
            if(conn.getResponseCode()==200){
                isConn = true;
            }
            
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            conn.disconnect();
        }
        return isConn;
    }


refer:http://stackoverflow.com/questions/19162272/httpclient-executehttppost-on-android-4-2-error


Android判断服务器是否开启,试了很多方法都不行(若server未开启会卡在HttpResponse那),有人说高版本的Android程序不允许在主线程中访问网络(主线程中可以读写网络流)有待于验证。(更正:不是说的不允许访问,而是很耗时,会假死(不耗时则不会假死);正解:当用户点击一个按钮时如果执行的是一个常耗时操作的话,处理不好会导致系统假死,用户体验很差,而Android则更进一步,如果任意一个Acitivity没有响应5秒钟以上就会被强制关闭,因此我们需要另外起动一个线程来处理长耗时操作,而主线程则不受其影响,在耗时操作完结发送消息给主线程,主线程再做相应处理。那么线程之间的消息传递和异步处理用的就是Handler。


方法一:

在xxxActivity的onCreate()方法中添加

[java]  view plain   copy
  View code snippets on CODE Derived into my code piece
  1. StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();  
  2. StrictMode.setThreadPolicy(policy);  

这两句代码在我写的Activity中本来就添加着,这个方法没有解决我的问题,go on.....


solution 2:

[java]  view plain   copy
  View code snippets on CODE Derived into my code piece
  1. package siat.hpc.ngb.utils;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import org.apache.http.HttpResponse;  
  6. import org.apache.http.client.ClientProtocolException;  
  7. import org.apache.http.client.HttpClient;  
  8. import org.apache.http.client.methods.HttpGet;  
  9. import org.apache.http.impl.client.DefaultHttpClient;  
  10. import org.apache.http.params.BasicHttpParams;  
  11. import org.apache.http.params.HttpConnectionParams;  
  12. import org.apache.http.params.HttpParams;  
  13.   
  14. import android.os.AsyncTask;  
  15. import android.util.Log;  
  16.   
  17. public class ConnServer extends AsyncTask<String,String,String>{  
  18.       
  19.     /** 
  20.      *  
  21.      * 判断服务器是否开启 
  22.      * @param  path   网络服务器地址 
  23.      * @return  
  24.      * 服务器开启 
  25.      * 服务器未开启 
  26.      */  
  27.       
  28.     @Override  
  29.     protected String doInBackground(String... params) {  
  30.         // TODO Auto-generated method stub  
  31.           
  32.           
  33.         try {  
  34.             HttpGet get = new HttpGet(params[0]);  
  35. Log.i("doInBack1...",params[0]);  
  36.             HttpResponse response = new DefaultHttpClient().execute(get);  
  37.               
  38. Log.i("doInBack2...",params[0]);  
  39.             if(response.getStatusLine().getStatusCode() == 200){  
  40.                 return "success";  
  41.             }   
  42.         } catch (ClientProtocolException e) {  
  43.             // TODO Auto-generated catch block  
  44.             e.printStackTrace();  
  45.             return "ClientError";  
  46.         } catch (IOException e) {  
  47.             // TODO Auto-generated catch block  
  48.             e.printStackTrace();  
  49.             return "ServerError";  
  50.         }  
  51.         return"success";   
  52.     }  
  53. }  

Call directly where needed:

The following direct call cannot obtain the return value of the String type. It returns an Object object. For the specific acquisition method, please refer to:

Android has two ways to get the return value of AsyncTask.  This article

[java]  view plain   copy
  View code snippets on CODE Derived into my code piece
  1. if(new ConnServer().execute(AppConstant.BASE_URL).equals("success")){   
[java]  view plain   copy
  View code snippets on CODE Derived into my code piece
  1. . . . <pre name= "code" class = "java"  style= "font-size: 18px;" >. . AppConstant.BASE_URL is an http string: such as http://172.21.6.233:8080/   

 
[java]  view plain   copy
  View code snippets on CODE Derived into my code piece
  1. }  
Method three:
采用Http方式:

复制代码
public boolean isConnByHttp(){
        boolean isConn = false;
        URL url;
        HttpURLConnection conn = null;
        try {
            url = new URL("ttp://wl.daishu001.com/YHDriver.asmx");
            conn = (HttpURLConnection)url.openConnection();
            conn.setConnectTimeout(1000*5);
            if(conn.getResponseCode()==200){
                isConn = true;
            }
            
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            conn.disconnect();
        }
        return isConn;
    }


refer:http://stackoverflow.com/questions/19162272/httpclient-executehttppost-on-android-4-2-error 方法三:
采用Http方式:

复制代码
public boolean isConnByHttp(){
        boolean isConn = false;
        URL url;
        HttpURLConnection conn = null;
        try {
            url = new URL("ttp://wl.daishu001.com/YHDriver.asmx");
            conn = (HttpURLConnection)url.openConnection();
            conn.setConnectTimeout(1000*5);
            if(conn.getResponseCode()==200){
                isConn = true;
            }
            
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            conn.disconnect();
        }
        return isConn;
    }


Guess you like

Origin blog.csdn.net/H_shaohui/article/details/70213360