如何解决java.net.UnknownHostException

时间:2016-05-19 05:40:50

标签: android unknown-host

我在清单文件中获得了互联网权限。我的移动网络连接也正常。

/**
 * Created by Yogesh on 5/07/2016.
 */
public class All_Item_Fragment extends android.support.v4.app.ListFragment {
    // Declare Variables
    JSONArray jsonarray = null;
    ListView list;
    ListViewAdapter adapter;
    ArrayList<HashMap<String, String>> itemlist;
    static String NAME = "name";
    static String DESCRIPTION = "Description";
    static String PRICE = "price";
    static String IMAGE = "image_path";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.all_item_layout, container, false);
        itemlist = new ArrayList<HashMap<String, String>>();
        new ReadJSON().execute();
        list = (ListView) view.findViewById(android.R.id.list);

        return view;
    }

    private class ReadJSON extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            itemlist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address
            JSONObject jsonobject = JSONfunctions.getJSONfromURL("http://mahatiffin.com/web/selectallmenu.php");

            try {
                // Locate the array name in JSON
                jsonarray = jsonobject.getJSONArray("AllMenu");

                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    map.put("name", jsonobject.getString("name"));
                    map.put("Description", jsonobject.getString("Description"));
                    map.put("price", jsonobject.getString("price"));
                    map.put("image_path", jsonobject.getString("image_path"));
                    // Set the JSON Objects into the array
                    itemlist.add(map);
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            // Pass the results into ListViewAdapter.java
            adapter = new ListViewAdapter(getActivity(), itemlist);
            // Set the adapter to the ListView
            list.setAdapter((ListAdapter) adapter);
        }
    }
}


public class JSONfunctions {
    public static JSONObject getJSONfromURL(String url) {
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;

        // Download JSON data from URL
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        // Convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        try {

            jArray = new JSONObject(result);
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        return jArray;
    }
}

在may片段页面中没有任何内容显示只显示空白页面..

  

05-18 17:43:11.730 27019-27019 / com.androidbelieve.MahaTiffin D / dalvikvm:VFY:将代码0x6f替换为0x0000       05-18 17:43:11.740 27019-27082 / com.androidbelieve.MahaTiffin E / log_tag:转换结果java.lang.NullPointerException时出错       05-18 17:43:11.740 27019-27082 / com.androidbelieve.MahaTiffin E / log_tag:解析数据时出错org.json.JSONException:字符0处的输入结束       05-18 17:43:11.770 27019-27082 / com.androidbelieve.MahaTiffin W / dalvikvm:threadid = 12:线程退出,未捕获异常(group = 0x40e11378)       05-18 17:43:11.770 27019-27082 / com.androidbelieve.MahaTiffin E / AndroidRuntime:FATAL EXCEPTION:AsyncTask#1       java.lang.RuntimeException:执行doInBackground()时发生错误       在android.os.AsyncTask $ 3.done(AsyncTask.java:299)       at java.util.concurrent.FutureTask $ Sync.innerSetException(FutureTask.java:273)       at java.util.concurrent.FutureTask.setException(FutureTask.java:124)       at java.util.concurrent.FutureTask $ Sync.innerRun(FutureTask.java:307)       at java.util.concurrent.FutureTas ...(FutureTask.java:137)       在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:230)       在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)       at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:569)       在java.lang.Thread.run(Thread.java:856)       引起:java.lang.NullPointerException       在com.androidbelieve.MahaTiffin.All_Item_Fragment $ ReadJSON.doInBackground(All_Item_Fragment.java:58)       在com.androidbelieve.MahaTiffin.All_Item_Fragment $ ReadJSON.doInBackground(All_Item_Fragment.java:43)       在android.os.AsyncTask $ 2.call(AsyncTask.java:287)       at java.util.concurrent.FutureTask $ Sync.innerRun(FutureTask.java:305)       at java.util.concurrent.FutureTas ...(FutureTask.java:137)       在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:230)       在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)       at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:569)       在java.lang.Thread.run(Thread.java:856)       05-18 17:43:12.420 27019-27019 / com.androidbelieve.MahaTiffin W / FragmentManager:moveToState:Veg_Item_Fragment的片段状态{415d7030#1 id = 0x7f0c00a0 android:switcher:2131493024:1}未内联更新;预期状态3发现2       05-18 17:43:12.530 27019-27104 / com.androidbelieve.MahaTiffin E / log_tag:http连接错误java.net.UnknownHostException:无法解析主机&#34; mahatiffin.com&#34;:没有与之关联的地址主机名       05-18 17:43:12.540 27019-27104 / com.androidbelieve.MahaTiffin E / log_tag:转换结果java.lang.NullPointerException时出错       05-18 17:43:12.540 27019-27104 / com.androidbelieve.MahaTiffin E / log_tag:解析数据时出错org.json.JSONException:字符0处的输入结束       05-18 17:43:12.570 27019-27104 / com.androidbelieve.MahaTiffin W / dalvikvm:threadid = 14:线程退出时未捕获异常(group = 0x40e11378)       05-18 17:43:12.570 27019-27104 / com.androidbelieve.MahaTiffin I / Process:发送信号。 PID:27019 SIG:9

我该如何解决这个问题..

2 个答案:

答案 0 :(得分:5)

原因:当您无法解析您提供的网址的DNS记录时,通常会触发UnknownHostException。该操作有一个合理的超时,但如果您的Wi-Fi连接较弱或设备上没有足够的信号,则在发送请求和接收响应之间可能会中断通信,因此您的设备没有收到回复,因此它认为这是DNS超时。

长话短说,有两个主要的例外原因:

  1. 如果您的Wi-Fi信号很弱。
  2. 如果您的设备已连接至Wi-Fi,但无法使用互联网。
  3. 解决方案:请求之前检查互联网的可用性

    public static boolean isInternetOn(Context context) {
    
        if (isMobileOrWifiConnectivityAvailable(context)) {
            try {
                HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
                urlc.setRequestProperty("User-Agent", "Test");
                urlc.setRequestProperty("Connection", "close");
                urlc.setConnectTimeout(1500);
                urlc.connect();
                return (urlc.getResponseCode() == 200);
            } catch (Exception e) {
              DebugLog.console("Couldn't check internet connection Exception is : " + e);
            }
        } else {
            DebugLog.console("Internet not available!");
        }
        return false;
    }
    
    
    public static boolean isMobileOrWifiConnectivityAvailable(Context ctx) {
        boolean haveConnectedWifi = false;
        boolean haveConnectedMobile = false;
    
    
        try {
            ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo[] netInfo = cm.getAllNetworkInfo();
            for (NetworkInfo ni : netInfo) {
                if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                    if (ni.isConnected()) {
                        haveConnectedWifi = true;
                    }
                if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                    if (ni.isConnected()) {
                        haveConnectedMobile = true;
                    }
            }
        } catch (Exception e) {
            DebugLog.console("[ConnectionVerifier] inside isInternetOn() Exception is : " + e.toString());
        }
        return haveConnectedWifi || haveConnectedMobile;
    }
    

答案 1 :(得分:0)

  connection successful
    {
    "AllMenu": [{
        "0": "3",
        "menu_id": "3",
        "1": "Aloo Parathas",
        "name": "Aloo Parathas",
        "2": "170",
        "price": "170",
        "3": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "Description": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "4": "http:\/\/mahatiffin.com\/uploads\/1.jpg",
        "image_path": "http:\/\/mahatiffin.com\/uploads\/1.jpg",
        "5": "Regular-menu",
        "menu_cat": "Regular-menu",
        "6": "1",
        "type_id": "1"
    }, {
        "0": "7",
        "menu_id": "7",
        "1": "ZzaxZxszsc",
        "name": "ZzaxZxszsc",
        "2": "343",
        "price": "343",
        "3": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "Description": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "4": "http:\/\/mahatiffin.com\/uploads\/2.jpg",
        "image_path": "http:\/\/mahatiffin.com\/uploads\/2.jpg",
        "5": "Regular-menu",
        "menu_cat": "Regular-menu",
        "6": "1",
        "type_id": "1"
    }, {
        "0": "8",
        "menu_id": "8",
        "1": "sdcsdvsd",
        "name": "sdcsdvsd",
        "2": "435",
        "price": "435",
        "3": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "Description": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "4": "http:\/\/mahatiffin.com\/uploads\/3.jpg",
        "image_path": "http:\/\/mahatiffin.com\/uploads\/3.jpg",
        "5": "Special-menu",
        "menu_cat": "Special-menu",
        "6": "2",
        "type_id": "2"
    }, {
        "0": "9",
        "menu_id": "9",
        "1": "sadcasc",
        "name": "sadcasc",
        "2": "435",
        "price": "435",
        "3": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "Description": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "4": "http:\/\/mahatiffin.com\/uploads\/4.jpg",
        "image_path": "http:\/\/mahatiffin.com\/uploads\/4.jpg",
        "5": "Regular-menu",
        "menu_cat": "Regular-menu",
        "6": "2",
        "type_id": "2"
    }, {
        "0": "10",
        "menu_id": "10",
        "1": "sadcasc",
        "name": "sadcasc",
        "2": "456",
        "price": "456",
        "3": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "Description": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "4": "http:\/\/mahatiffin.com\/uploads\/5.jpg",
        "image_path": "http:\/\/mahatiffin.com\/uploads\/5.jpg",
        "5": "Regular-menu",
        "menu_cat": "Regular-menu",
        "6": "1",
        "type_id": "1"
    }, {
        "0": "11",
        "menu_id": "11",
        "1": "sda",
        "name": "sda",
        "2": "234",
        "price": "234",
        "3": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "Description": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "4": "http:\/\/mahatiffin.com\/uploads\/6.JPG",
        "image_path": "http:\/\/mahatiffin.com\/uploads\/6.JPG",
        "5": "Special-menu",
        "menu_cat": "Special-menu",
        "6": "2",
        "type_id": "2"
    }, {
        "0": "12",
        "menu_id": "12",
        "1": "sadcasc",
        "name": "sadcasc",
        "2": "324",
        "price": "324",
        "3": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "Description": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "4": "http:\/\/mahatiffin.com\/uploads\/7.JPEG",
        "image_path": "http:\/\/mahatiffin.com\/uploads\/7.JPEG",
        "5": "Regular-menu",
        "menu_cat": "Regular-menu",
        "6": "1",
        "type_id": "1"
    }, {
        "0": "14",
        "menu_id": "14",
        "1": "sadcasc",
        "name": "sadcasc",
        "2": "232",
        "price": "232",
        "3": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "Description": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "4": "http:\/\/mahatiffin.com\/uploads\/1.jpg",
        "image_path": "http:\/\/mahatiffin.com\/uploads\/1.jpg",
        "5": "Special-menu",
        "menu_cat": "Special-menu",
        "6": "1",
        "type_id": "1"
    }, {
        "0": "15",
        "menu_id": "15",
        "1": "sadcasc",
        "name": "sadcasc",
        "2": "325",
        "price": "325",
        "3": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "Description": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "4": "http:\/\/mahatiffin.com\/uploads\/2.jpg",
        "image_path": "http:\/\/mahatiffin.com\/uploads\/2.jpg",
        "5": "Special-menu",
        "menu_cat": "Special-menu",
        "6": "2",
        "type_id": "2"
    }, {
        "0": "16",
        "menu_id": "16",
        "1": "sadcasc",
        "name": "sadcasc",
        "2": "344",
        "price": "344",
        "3": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "Description": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "4": "http:\/\/mahatiffin.com\/uploads\/4.jpg",
        "image_path": "http:\/\/mahatiffin.com\/uploads\/4.jpg",
        "5": "Regular-menu",
        "menu_cat": "Regular-menu",
        "6": "1",
        "type_id": "1"
    }, {
        "0": "18",
        "menu_id": "18",
        "1": "edfwdfewr",
        "name": "edfwdfewr",
        "2": "23",
        "price": "23",
        "3": "xasx scasc dqedqd edbhwd dwh3ej1 1wh1e2ue 3eh3ue e2euh23ueej ewnwencj",
        "Description": "xasx scasc dqedqd edbhwd dwh3ej1 1wh1e2ue 3eh3ue e2euh23ueej ewnwencj",
        "4": "http:\/\/mahatiffin.com\/uploads\/4.jpg",
        "image_path": "http:\/\/mahatiffin.com\/uploads\/4.jpg",
        "5": "Regular-menu",
        "menu_cat": "Regular-menu",
        "6": "2",
        "type_id": "2"
    }, {
        "0": "19",
        "menu_id": "19",
        "1": "Aloo Gobi",
        "name": "Aloo Gobi",
        "2": "250",
        "price": "250",
        "3": "Aloo Sabzi, 2 Puris, Rice, Dal, Shrikhand",
        "Description": "Aloo Sabzi, 2 Puris, Rice, Dal, Shrikhand",
        "4": "http:\/\/mahatiffin.com\/uploads\/1.jpg",
        "image_path": "http:\/\/mahatiffin.com\/uploads\/1.jpg",
        "5": "Special-menu",
        "menu_cat": "Special-menu",
        "6": "1",
        "type_id": "1"
    }]
}

删除String&#34;连接成功&#34;来自Php Json的页面开头。

2)问题类强制转换异常:如下所示:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.all_item_layout, container, false);
        itemlist = new ArrayList<HashMap<String, String>>();
        new ReadJSON().execute();
        list = (ListView) view.findViewById(android.R.id.list);

        // Pass the results into ListViewAdapter.java
        adapter = new ListViewAdapter(getActivity(), itemlist);
        // Set the adapter to the ListView
        list.setAdapter((ListAdapter) adapter);
        return view;
    }

@Override
        protected void onPostExecute(Void args) {
          adapter.notifydatasetchanged();
        }

删除&#34; itemlist = new ArrayList&gt;(); &#34;来自doInBackground()方法。