標籤:網路伺服器 asynctask 線程 android url
Android判斷伺服器是否開啟,試了很多方法都不行(若server未開啟會卡在HttpResponse那),有人說高版本的Android程式不允許在主線程中訪問網路(主線程中可以讀寫網路流)有待於驗證。
方法一:
在xxxActivity的onCreate()方法中添加
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();StrictMode.setThreadPolicy(policy);
這兩句代碼在我寫的Activity中本來就添加著,這個方法沒有解決我的問題,go on.....
solution 2:
package siat.hpc.ngb.utils;import java.io.IOException;import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.params.BasicHttpParams;import org.apache.http.params.HttpConnectionParams;import org.apache.http.params.HttpParams;import android.os.AsyncTask;import android.util.Log;public class ConnServer extends AsyncTask<String,String,String>{/** * * 判斷伺服器是否開啟 * @param path 網路伺服器地址 * @return * 伺服器開啟 * 伺服器未開啟 */@Overrideprotected String doInBackground(String... params) {// TODO Auto-generated method stubtry {HttpGet get = new HttpGet(params[0]);Log.i("doInBack1...",params[0]);HttpResponse response = new DefaultHttpClient().execute(get);Log.i("doInBack2...",params[0]);if(response.getStatusLine().getStatusCode() == 200){return "success";} } catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();return "ClientError";} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();return "ServerError";}return "success";}}
在需要的地方直接調用:
if(new ConnServer().execute(AppConstant.BASE_URL).equals("success")){
。。。<pre name="code" class="java" style="font-size: 18px;">。。AppConstant.BASE_URL是一個http的字串:如http://172.21.6.233:8080/
}
refer:http://stackoverflow.com/questions/19162272/httpclient-executehttppost-on-android-4-2-error
Android用戶端判斷伺服器是否開啟 HttpHostException解決方案