【问题标题】:JSONParser: IOException: Unable to resolve host "my host address": No address associated with hostnameJSONParser:IOException:无法解析主机“我的主机地址”:没有与主机名关联的地址
【发布时间】:2019-07-10 18:36:03
【问题描述】:

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

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

活动类:

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();
    }
}

它说,未知主机。

【问题讨论】:

    标签: java android json


    【解决方案1】:

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

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

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

    【讨论】:

    • 当我使用这个链接时,我可以通过web从服务器访问json格式的数据。但是在android studio中它实际上并没有与服务器连接。我认为它需要更多的代码段。在 android studio 中,当我在网上浏览此地址时,它说无法同时找到该地址,它给出了正确的输出。
    • 这就是我被指出的。从您在上面发布的代码中,该 URL 看起来格式不正确(中间有一个空格)。您需要按照我的回答中的建议首先删除格式错误的 URL。你试过调查吗?如果这不起作用,请告诉我。
    猜你喜欢
    • 1970-01-01
    • 2017-12-04
    • 2018-12-04
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 2013-09-07
    • 2016-02-12
    • 1970-01-01
    相关资源
    最近更新 更多