简体   繁体   中英

java android application cannot make http get

Can someone helps me to get json from the web.In the end of function jsonResponse is empty. I use this method to do it:

 private String getJson() {

    jsonResponsce = "";

    AsyncTask.execute(new Runnable() {
        @Override
        public void run() {
            try{

                URL httpbinEndpoint = new URL(webPage);
                HttpsURLConnection myConnection = (HttpsURLConnection) httpbinEndpoint.openConnection();

                myConnection.setRequestMethod("GET");

                // Enable writing
                myConnection.setDoOutput(true);

                String internetData = "";

                // Write the data
                myConnection.getOutputStream().write(internetData.getBytes());

                jsonResponsce = internetData;

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

    return jsonResponsce;
}

I set an Internet permission to the manifest. I try go get Json from the next address: https://shori-dodjo-mobile-app.firebaseio.com/.json . Full code is placed here: https://github.com/GenkoKaradimov/Shori-Dodjo-Android-App/

You are executing the request asynchronously so the method starts the execution and then completes and therefore there is no result. The result will be there in a second but by that time the method getJson has already completed. You most probably need to put the code that uses the json at the end of the run method.

In addition your code for reading from the stream seems wrong. It should probably be something like

BufferedReader br = new BufferedReader(new InputStreamReader(myConnection.getInputStream()));

jsonResponsce = br.lines().collect(Collectors.joining("\n"));

(I haven't tested this)

There are multiple issues in your code:

First, AsyncTask means it's async(hronous), so you can't return the result right away. Instead, override AsyncTask 's onPostExecute and do what you need to do with the data there. Here is the sample implementation.

Second, you're using getOutputStream , which is intended for writing to the connection, ie sending data to the server. In your case you need to getInputStream and read from it. Easiest way is to wrap it in a BufferedReader and read until it returns -1 (marking end of stream), and then convert to string.

There are a few quirks: You should handle, or at least recognize errors by checking HTTP status code, handle encodings (the convert-bytes-to-string part), and handle cases when response is compressed, eg using DEFLATE or gzip. I've implemented that in a pure Java way ( reference code , warning: outdated docs), but I'd seriously recommend using one of the established libraries such as Retrofit or Volley .

I think you will be better off using Volley. Here is a good example of the usage: https://stackoverflow.com/a/42601290/1450032

Json objects usually get return as HashMaps. So you might need something like, HashMap yourMap = new HashMap<~>(); then yourMap.get("the objects name on the other side", the var its getting saved too.); right now it looks like all you are trying to do is save the byte data, but this byte data needs to have a type. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM