JSONParser:IOException:无法解析主机“我的主机地址”:没有与主机名关联的地址

时间:2019-07-10 18:36:03

标签: java android json

我正在尝试从存储在我的在线托管服务器(00webhost.com)中的JSON文件中写入的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();
    }
}

它说,未知主机。

1 个答案:

答案 0 :(得分:0)

好像URL的格式不正确。我认为网址的两个部分之间有一个空格。

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

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