java - JSON 解析器 : IOException: Unable to resolve host "my host address": No address associated with hostname

标签 java android json

我正在尝试从一个 JSON 文件中获取数据,该文件是用 PHP 文件编写的,该文件存储在我的在线托管服务器 (00webhost.com) 中。当我运行我的程序时,它显示未知主机。但是,地址会给出JSON格式的文件。

我在 AndroidManifest.xml 文件中拥有所有权限以及互联网权限。

Activity 类:

public class Recmain extends AppCompatActivity {
    private String TAG = MainActivity.class.getSimpleName();
    private ListView lv;

    ArrayList<HashMap<String, String>> contactList;

    TextView uid;
    TextView name1;
    TextView email1;
    Button Btngetdata;

    //URL to get JSON Array
    private static String url = "http://tongue-tied- 
      papers.000webhostapp.com/data_fetch.php";

    //JSON Node Names
    private static final String TAG_USER = "user";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";
    private static final String TAG_EMAIL = "email";

    JSONArray user = null;

    private List<movie> movieList = new ArrayList<>();
    private RecyclerView recyclerView;
    private moviesadapter mAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rmain);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        Intent intent=getIntent();
        String m=intent.getStringExtra("data");
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mAdapter = new moviesadapter(movieList);
        RecyclerView.LayoutManager mLayoutManager = new 
     LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mAdapter);
        prepareMovieData();
    }

    private void prepareMovieData(){
        movie movie = new movie("Mad Max: Fury Road", "Action & Adventure", 
        "2015");
        movieList.add(movie);
        mAdapter.notifyDataSetChanged();
        new GetContacts().execute();
    }


    private class GetContacts extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Toast.makeText(recmain.this,url,Toast.LENGTH_LONG).show();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            JSONParser sh = new JSONParser();
            // Making a request to url and getting response
            String url = "https://tongue-tied- 
      papers.000webhostapp.com/data_fetch.php";
            String jsonStr = sh.makeServiceCall(url);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    JSONArray contacts = jsonObj.getJSONArray("id");

                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);
                        String id = c.getString("id");

                          Toast.makeText(getApplicationContext(), id , 
        Toast.LENGTH_LONG).show();


                        // tmp hash map for single contact
                        HashMap<String, String> contact = new HashMap<>();

                        // adding each child node to HashMap key => value
                        contact.put("id", id);


                        // adding contact to contact list
                        contactList.add(contact);
                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG).show();
                        }
                    });

                }

            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat 
    for possible errors!",
                                Toast.LENGTH_LONG).show();
                    }
                });
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {

        }
    }
}

适配器类:

public class JSONParser {

    private static final String TAG = JSONParser.class.getSimpleName();

    public JSONParser() {
    }

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);

            HttpURLConnection conn = (HttpURLConnection) 
    url.openConnection();
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new 
    InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }
}

它说,未知主机。

最佳答案

URL 的格式似乎不正确。我认为 URL 的两部分之间有一个空格。

private static String url = "http://tongue-tied-papers.000webhostapp.com/data_fetch.php"

请尝试使用上面的 URL,tied-papers 之间不要有任何空格。您有两个单独的 URL 声明,一个在类的开头,另一个在 doInBackground 方法中。请尝试更改两者。

关于java - JSON 解析器 : IOException: Unable to resolve host "my host address": No address associated with hostname,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56976758/

相关文章:

java - 图像上弹出文本的 CSS 帮助

java - 将对象传递给 DROOLS

Android Edittext 光标不可见

android - 如何在android中使用带双参数的AsyncTask

php - 从 PHP 数组到 Javascript 数组大括号与方括号

javascript - 将 JSON 对象重新映射到其他 JSON 结构

java - 查找树高时的stackoverflow

java - 带有 com.mysql.jdbc.ReplicationDriver 的 MySql Master/Slave Spring Hibernate

android - 是否有API可以访问移动设备上的位置记录?

python - 将 CSV 转换为嵌套 JSON,同时将特定键的值格式化为 numeric/int/float