0

When trying my app on lower api levels such as 15 or 19(on emulators and real devices), i get a UnknownHostException for a specific URL: http://jotihunt-api_v2.mysite123.nl/login mysite123 is fictional. But i don't get a UnknownHostException for other urls such as that of google . So i seems the URL is wrong, but on API level 22 for example i don't get this exception. I have a Internet Connection and i have the required permissions:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

I use this code to execute post/get requests to a web API:

    @Override
    protected List<WebResponse> doInBackground(WebRequest... params) {
        ArrayList<WebResponse> responses = new ArrayList<>();
        WebRequest current;

        for(int i = 0; i < params.length; i++)
        {
            current = params[i];

            try {
                InetAddress address = InetAddress.getByName(current.getUrl().getHost());
                Log.i("WebRequestTask", address.toString());
            } catch (UnknownHostException exception) {
                Log.e("WebRequestTask", exception.toString(), exception);
            }


            TRYCATCH:
            try
            {
                if(current.getUrl() == null) break TRYCATCH;

                HttpURLConnection connection = (HttpURLConnection)current.getUrl().openConnection();

                switch (current.getMethod())
                {
                    case WebRequestMethod.POST:
                        if(current.hasData())
                        {
                            connection.setDoOutput(true);
                            connection.setRequestMethod(WebRequestMethod.POST);

                            OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream());
                            streamWriter.write(current.getData());
                            streamWriter.flush();
                            streamWriter.close();
                        }
                        break;
                }

                InputStream response;
                if(connection.getResponseCode() == 200)
                {
                         /*
                        * Get the response stream.
                        * */
                    response = connection.getInputStream();
                }
                else
                {
                        /*
                        * Get the error stream.
                        * */
                    response = connection.getErrorStream();
                }

                /**
                 * Read the stream.
                 * */
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response));
                StringBuilder builder = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    builder.append(line);
                }
                bufferedReader.close();

                /**
                 * Create a response
                 * */
                responses.add(new WebResponse(current, builder.toString(), connection.getResponseCode()));

                current.setExecutionDate(new Date());

                connection.disconnect();

            }
            catch(Exception e)
            {
                /**
                 * Print the stack trace
                 * */
                e.printStackTrace();

                /**
                 * Log a error.
                 * */
                Log.e("WebRequestTask", e.toString(), e);

                /**
                 * Add a response with as text the error message
                 * */
                responses.add(new WebResponse(current, e.toString(), 0));
            }
        }
        return responses;
    }

The state of the objects: https://i.stack.imgur.com/Zrc7q.jpg

The creation and execution of the request:

WebRequest request = new WebRequest.Builder()
            .setId(MY_REQUEST_ID)
            .setMethod(WebRequestMethod.POST)
            .setUrl(new UrlBuilder().append("http://jotihunt-api_v2.mysite123.nl/login").build())
            .setData("sfsf")
            .create();
    request.executeAsync(new WebRequest.OnWebRequestCompletedCallback() {
        @Override
        public void onWebRequestCompleted(WebResponse response) {
            Log.i("",response.getData());
        }
    });

This is the exception i get:

08-16 12:33:36.340 4277-4356/nl.rsdt.japp W/System.err: java.net.UnknownHostException: http://jotihunt-api_v2.mysite123.nl/login
08-16 12:33:36.342 4277-4356/nl.rsdt.japp W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:279)
08-16 12:33:36.344 4277-4356/nl.rsdt.japp W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
08-16 12:33:36.346 4277-4356/nl.rsdt.japp W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
08-16 12:33:36.348 4277-4356/nl.rsdt.japp W/System.err:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
08-16 12:33:36.352 4277-4356/nl.rsdt.japp W/System.err:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
08-16 12:33:36.355 4277-4356/nl.rsdt.japp W/System.err:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197)
08-16 12:33:36.356 4277-4356/nl.rsdt.japp W/System.err:     at com.rsdt.anl.WebRequestTask.doInBackground(WebRequestTask.java:53)
08-16 12:33:36.357 4277-4356/nl.rsdt.japp W/System.err:     at com.rsdt.anl.WebRequestTask.doInBackground(WebRequestTask.java:21)
08-16 12:33:36.358 4277-4356/nl.rsdt.japp W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:288)
08-16 12:33:36.359 4277-4356/nl.rsdt.japp W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
08-16 12:33:36.360 4277-4356/nl.rsdt.japp W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
08-16 12:33:36.365 4277-4356/nl.rsdt.japp W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
08-16 12:33:36.372 4277-4356/nl.rsdt.japp W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
08-16 12:33:36.373 4277-4356/nl.rsdt.japp W/System.err:     at java.lang.Thread.run(Thread.java:848)

UPDATE I can resolve the host with InetAdress, but it still doesn't work

UPDATE 2 I found similar issues after some more googling, it seems that underscores are not valid URLs characters.

Sources:

(i cannot include more than 2 links so i left the begin of the link out)

stackoverflow.com/questions/36074952/unknown-host-exception-using-emulator-and-httpurlconnection

code.google.com/p/android/issues/detail?id=37577

github.com/google/ExoPlayer/issues/239

Bram Sinke
  • 193
  • 8
  • Hey see this [link](http://stackoverflow.com/questions/6484275/java-net-unknownhostexception-invalid-hostname-for-server-local) I think your domain does not exist. – Sagar Gangawane Aug 16 '16 at 11:25
  • may be this will help. http://stackoverflow.com/questions/3293659/android-java-net-unknownhostexception-host-is-unresolved-strategy-question – Dipali Shah Aug 16 '16 at 11:26
  • That URL returns a 404 error in a desktop Web browser. – CommonsWare Aug 16 '16 at 11:36
  • Error 101 in browser. `404 : Not Found || ERROR 101 : FOUTIEVE [REQUEST_METHOD][GET/POST]. || login`. Has nothing to do with an unknown host. The server responds. – greenapps Aug 16 '16 at 11:37
  • @SagarGangawane the domain exists you can ping it via cmd: ping jotihunt-api_v2.area348.nl – Bram Sinke Aug 16 '16 at 11:40
  • There is something with the used DNS servers on those devices. As they have to resolve the host. Try other ones. – greenapps Aug 16 '16 at 11:41
  • @Dipalishah I have tried it, but it doesn't work – Bram Sinke Aug 16 '16 at 11:41
  • @greenapps The 404 has do to with the API it returns a 404 if the input was not correct, but the problem is not there because it cannot resolve the host – Bram Sinke Aug 16 '16 at 11:44
  • Dont tell me. I just told so. – greenapps Aug 16 '16 at 11:44
  • Please, read [this (how to ask)](http://stackoverflow.com/help/how-to-ask) and [this (mcve)](http://stackoverflow.com/help/mcve) before asking, as those will help you get more and better answers from the community. Demonstrate the `try/catch` you are handling. Also, show your `current` Object, as its possible that it is incomplete or in an unknown state, when getters are used. – Bonatti Aug 16 '16 at 12:10
  • @greenapps I'm sorry i misunderstood – Bram Sinke Aug 16 '16 at 13:04
  • @Bonatti I have updated my post, thanks! – Bram Sinke Aug 16 '16 at 13:09
  • Just to be sure, can you ensure that your `.setUrl` method is working as intended? The `append` appears to be doing some undesired effect.... I myself use [Volley](https://developer.android.com/training/volley/index.html) and never had any issues, I used OkHTTP and Picasso, some years ago, but replaced with Volley, for its caching system, as well as the way it handles most other libraries when they are available (such as the Apache HTTPconnection one)... Please, try setting your `setUrl` with a simple String, and [check if it works like this](http://stackoverflow.com/a/19168199/4903925). – Bonatti Aug 16 '16 at 13:31
  • @Bonatti I have downloaded Volley and tried it with my link hardcoded in `String url ="http://jotihunt-api_v2.area348.nl/login";`, but i get the same error. I have come across some issues that conclude that underscores are not valid chars for URLs. I'm going to change the host name and hope that resolves the issue. I will edit the post if the host name change fixes my problem. But for now thank you for helping me and learning me how to post :) – Bram Sinke Aug 16 '16 at 14:05
  • Do note that `_` is a "valid" char, it just has to be encoded, for instance the `http://jotihunt-ap‌​i_v2.area348.nl/login‌` can be encoded as [the percent rule system](https://en.wikipedia.org/wiki/Percent-encoding) `http%3A%2F%2Fjotihunt-ap%E2%80%8C%E2%80%8Bi_v2.area348.nl%2Flogin%E2%80%8C`, or any other URL related encode. In Volley, my "host" is usually weird. The undesired chars can be parsed directly and the String can just be `String yourURL= "http:/YOUR_HOST_GOES_HERE?q=" + Uri.encode(queryParameters);` for a GET. A POST, just override `protected Map getParams()` – Bonatti Aug 16 '16 at 14:34

1 Answers1

1

I changed the hostname so that is doesn't contain a underscore, this resolved my issues. It seems that the DNS on older android versions does not support URLs with a underscore

Sources:

Similiar issue

http://code.google.com/p/android/issues/detail?id=37577

Community
  • 1
  • 1
Bram Sinke
  • 193
  • 8