首页 > 代码库 > Android客户端判断服务器是否开启 HttpHostException解决方案

Android客户端判断服务器是否开启 HttpHostException解决方案


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 
	 * 服务器开启
	 * 服务器未开启
	 */
	
	@Override
	protected String doInBackground(String... params) {
		// TODO Auto-generated method stub
		
		
		try {
			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 block
			e.printStackTrace();
			return "ClientError";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.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解决方案