Android用戶端判斷伺服器是否開啟 HttpHostException解決方案

來源:互聯網
上載者:User

標籤:網路伺服器   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解決方案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.