In my Android application for reading RSS links, I am getting this error:
java.net.UnknownHostException:
Unable to resolve host «example.com»;
No address associated with hostname.
In my emulator I can connect to Google through a browser.
Please help me to resolve this issue.
asked Jun 15, 2011 at 9:14
bejoy georgebejoy george
29.3k5 gold badges19 silver badges15 bronze badges
10
You probably don’t have the INTERNET
permission. Try adding this to your AndroidManifest.xml
file, right before </manifest>
:
<uses-permission android:name="android.permission.INTERNET" />
Note: the above doesn’t have to be right before the </manifest>
tag, but that is a good / correct place to put it.
Note: if this answer doesn’t help in your case, read the other answers!
Stephen C
695k94 gold badges801 silver badges1210 bronze badges
answered Jun 15, 2011 at 9:57
4
I’ve seen this problem in the emulator as well. In my case, it is caused by launching the emulator, then putting the computer to sleep or changing the network connection (going from work to home, etc), then attempting to use the same emulator again. Closing and re-launching the emulator resolves the problem in this case.
answered May 10, 2013 at 17:20
Eric BrynsvoldEric Brynsvold
2,8303 gold badges17 silver badges22 bronze badges
7
It is WiFi bug due to wifi disable or not properly connected.
Simply Reconnect the wifi will solve the issue.
answered Jul 6, 2015 at 9:29
shehzyshehzy
2,1953 gold badges25 silver badges44 bronze badges
Unable to resolve host “”; No address associated with hostname
you must have to check below code here on your manifest :
<uses-permission android:name="android.permission.INTERNET" />
and most important at least for me:-
enabled wifi connection or internet connection on your mobile device
answered Jun 17, 2013 at 5:51
dugguduggu
37.7k12 gold badges116 silver badges113 bronze badges
2
Check you have:
1- Access to Internet connectivity.
2- The permission for internet is present in the manifest.
3- The url host is valid and registered in a trusted domain name server.
answered Apr 15, 2018 at 1:48
Sometimes, although you add <uses-permission android:name="android.permission.INTERNET" />
in the AndroidManifest and you have a WiFi connection, this exception can be thrown. In my case, I have turned off WiFi and then turned it on again. This resolved the error. Weird solution, but sometimes it works.
Jared Rummler
37.7k19 gold badges132 silver badges147 bronze badges
answered Jun 30, 2014 at 6:37
Batuhan CoşkunBatuhan Coşkun
2,9612 gold badges30 silver badges48 bronze badges
2
""
it seems you are trying to resolve this host , which is invalid.
Check for rss URL
Update
Following are the possibilities
1 Your browser is configured with proxy, app not
System.setProperty("http.proxyHost", "my.proxyhost.com");
System.setProperty("http.proxyPort", "1234");
2 Your browser has access to internet. not app
3 can be an SSL issue if URL is secured
answered Jun 15, 2011 at 9:16
jmjjmj
237k42 gold badges401 silver badges438 bronze badges
9
I had the same issue. My virtual device was showing a crossed-out WiFi icon at the top bar of the device. I rebooted the virtual device and everything was back to normal.
answered Apr 24, 2018 at 1:29
Fo NkoFo Nko
61210 silver badges21 bronze badges
Some times on the emulator, I have to launch the browser before my app can access the Internet.
answered Jun 15, 2011 at 11:48
SnicolasSnicolas
37.8k15 gold badges114 silver badges172 bronze badges
1
It could be due to below reasons: —
-
Either you dont have INTERNET permission in manifest file. If so then please use this statement
<uses-permission android:name="android.permission.INTERNET" />
-
Or you are connected to a network but your internet connection is not working. Like you are connected to a Wi-Fi but it doesnt have internet connection or Mobile data on your phone is ON but you dont have data connectivity on your phone.
Point# 2 is interesting and its not assumption, I have tested the same at my end.
Hope this will help you
Summved
answered Feb 23, 2017 at 10:27
Summved JainSummved Jain
8722 gold badges18 silver badges21 bronze badges
It’s not your fault bae, I’ve had this happen sometimes when the emulator’s in a weird state. Just restarting the emulator helped me.
answered Feb 10, 2016 at 0:55
Ed LeeEd Lee
1872 silver badges13 bronze badges
In my case, I had that error when I’m connected to VPN on my host but not on simulator. Turning the VPN off solved the issue
answered Jun 27, 2017 at 11:42
William KinaanWilliam Kinaan
28k20 gold badges85 silver badges118 bronze badges
In my case problem was with WIFI working with IPV6 and my domain did not have IPv6 adress
answered Dec 4, 2017 at 12:16
1
If you are running the app on an emulator, make sure that it is properly connected to the internet. If it is not, the easiest way of solving it is reopening the emulator or creating a new device.
answered Jan 15, 2015 at 11:47
Alex StylAlex Styl
3,8922 gold badges28 silver badges47 bronze badges
I Had the same problem, and it was because the simulator somehow got in airplane mode, once this was disabled my App worked fine
I had tried everything, rebuild, clean+build and reboot android studio and reboot the computer, even reinstalling android studio..
answered Dec 13, 2016 at 7:37
TWOcvfanTWOcvfan
3681 gold badge3 silver badges19 bronze badges
Check permission for INTERNET in mainfest file and check network connectivity.
answered Sep 21, 2016 at 18:49
In my Android application for reading RSS links, I am getting this error:
java.net.UnknownHostException:
Unable to resolve host «example.com»;
No address associated with hostname.
In my emulator I can connect to Google through a browser.
Please help me to resolve this issue.
asked Jun 15, 2011 at 9:14
bejoy georgebejoy george
29.3k5 gold badges19 silver badges15 bronze badges
10
You probably don’t have the INTERNET
permission. Try adding this to your AndroidManifest.xml
file, right before </manifest>
:
<uses-permission android:name="android.permission.INTERNET" />
Note: the above doesn’t have to be right before the </manifest>
tag, but that is a good / correct place to put it.
Note: if this answer doesn’t help in your case, read the other answers!
Stephen C
695k94 gold badges801 silver badges1210 bronze badges
answered Jun 15, 2011 at 9:57
4
I’ve seen this problem in the emulator as well. In my case, it is caused by launching the emulator, then putting the computer to sleep or changing the network connection (going from work to home, etc), then attempting to use the same emulator again. Closing and re-launching the emulator resolves the problem in this case.
answered May 10, 2013 at 17:20
Eric BrynsvoldEric Brynsvold
2,8303 gold badges17 silver badges22 bronze badges
7
It is WiFi bug due to wifi disable or not properly connected.
Simply Reconnect the wifi will solve the issue.
answered Jul 6, 2015 at 9:29
shehzyshehzy
2,1953 gold badges25 silver badges44 bronze badges
Unable to resolve host “”; No address associated with hostname
you must have to check below code here on your manifest :
<uses-permission android:name="android.permission.INTERNET" />
and most important at least for me:-
enabled wifi connection or internet connection on your mobile device
answered Jun 17, 2013 at 5:51
dugguduggu
37.7k12 gold badges116 silver badges113 bronze badges
2
Check you have:
1- Access to Internet connectivity.
2- The permission for internet is present in the manifest.
3- The url host is valid and registered in a trusted domain name server.
answered Apr 15, 2018 at 1:48
Sometimes, although you add <uses-permission android:name="android.permission.INTERNET" />
in the AndroidManifest and you have a WiFi connection, this exception can be thrown. In my case, I have turned off WiFi and then turned it on again. This resolved the error. Weird solution, but sometimes it works.
Jared Rummler
37.7k19 gold badges132 silver badges147 bronze badges
answered Jun 30, 2014 at 6:37
Batuhan CoşkunBatuhan Coşkun
2,9612 gold badges30 silver badges48 bronze badges
2
""
it seems you are trying to resolve this host , which is invalid.
Check for rss URL
Update
Following are the possibilities
1 Your browser is configured with proxy, app not
System.setProperty("http.proxyHost", "my.proxyhost.com");
System.setProperty("http.proxyPort", "1234");
2 Your browser has access to internet. not app
3 can be an SSL issue if URL is secured
answered Jun 15, 2011 at 9:16
jmjjmj
237k42 gold badges401 silver badges438 bronze badges
9
I had the same issue. My virtual device was showing a crossed-out WiFi icon at the top bar of the device. I rebooted the virtual device and everything was back to normal.
answered Apr 24, 2018 at 1:29
Fo NkoFo Nko
61210 silver badges21 bronze badges
Some times on the emulator, I have to launch the browser before my app can access the Internet.
answered Jun 15, 2011 at 11:48
SnicolasSnicolas
37.8k15 gold badges114 silver badges172 bronze badges
1
It could be due to below reasons: —
-
Either you dont have INTERNET permission in manifest file. If so then please use this statement
<uses-permission android:name="android.permission.INTERNET" />
-
Or you are connected to a network but your internet connection is not working. Like you are connected to a Wi-Fi but it doesnt have internet connection or Mobile data on your phone is ON but you dont have data connectivity on your phone.
Point# 2 is interesting and its not assumption, I have tested the same at my end.
Hope this will help you
Summved
answered Feb 23, 2017 at 10:27
Summved JainSummved Jain
8722 gold badges18 silver badges21 bronze badges
It’s not your fault bae, I’ve had this happen sometimes when the emulator’s in a weird state. Just restarting the emulator helped me.
answered Feb 10, 2016 at 0:55
Ed LeeEd Lee
1872 silver badges13 bronze badges
In my case, I had that error when I’m connected to VPN on my host but not on simulator. Turning the VPN off solved the issue
answered Jun 27, 2017 at 11:42
William KinaanWilliam Kinaan
28k20 gold badges85 silver badges118 bronze badges
In my case problem was with WIFI working with IPV6 and my domain did not have IPv6 adress
answered Dec 4, 2017 at 12:16
1
If you are running the app on an emulator, make sure that it is properly connected to the internet. If it is not, the easiest way of solving it is reopening the emulator or creating a new device.
answered Jan 15, 2015 at 11:47
Alex StylAlex Styl
3,8922 gold badges28 silver badges47 bronze badges
I Had the same problem, and it was because the simulator somehow got in airplane mode, once this was disabled my App worked fine
I had tried everything, rebuild, clean+build and reboot android studio and reboot the computer, even reinstalling android studio..
answered Dec 13, 2016 at 7:37
TWOcvfanTWOcvfan
3681 gold badge3 silver badges19 bronze badges
Check permission for INTERNET in mainfest file and check network connectivity.
answered Sep 21, 2016 at 18:49
This has been a long term problem with apt, and Ubuntu has never fixed it. Apt doesn’t seem to use the same DNS servers that the internal system does — ‘ping ‘ returns a correct IP address. Apt-get claims that the hostname isn’t found.
«Something wicked happened resolving ‘extras.ubuntu.com:http» (Which sounds, somewhat, like it’s trying to resolve a .com:http domain, which isn’t a valid TLD)
To modify /etc/hosts, use the following:
Ping each of the names that are failing to resolve —
PING extras.ubuntu.com (91.189.88.33) 56(84) bytes of data.
Use your favourite editor, such as vi — ‘sudo vi /etc/hosts’.
Scroll down to the end, and add a line such as the following
91.189.88.33 extras.ubuntu.com (with the appropriate name and IP address. IP is first)
Save the file, then re-run apt-get. Once you’ve run apt-get, edit /etc/hosts again, and comment out the line with a hash mark — #. (or delete it entirely)
#91.189.88.33 extras.ubuntu.com
The reason to comment out/delete the line is that Ubuntu apparently shuffles their servers around randomly, and that might not be the correct IP the next time.
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Closed
techyrajeev opened this issue
Jul 23, 2018
· 34 comments
Comments
Getting this error while calling api.
Sometimes I receive response occasionally. I tested the api using postman it is working perfectly fine.
Version: http: ^0.11.3+16
[ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception: E/flutter (24807): SocketException: Failed host lookup: 'api.xyz.com' (OS Error: No address associated with hostname, errno = 7) E/flutter (24807): #0 IOClient.send (package:http/src/io_client.dart:30:23) E/flutter (24807): <asynchronous suspension> E/flutter (24807): #1 BaseClient._sendUnstreamed (package:http/src/base_client.dart:171:38) E/flutter (24807): <asynchronous suspension> E/flutter (24807): #2 BaseClient.post (package:http/src/base_client.dart:56:5) E/flutter (24807): #3 post.<anonymous closure> (package:http/http.dart:70:34) E/flutter (24807): #4 _withClient (package:http/http.dart:167:20) E/flutter (24807): <asynchronous suspension> E/flutter (24807): #5 post (package:http/http.dart:70:3) E/flutter (24807): #6 NetworkUtil.post (package:ddictor/utils/network_util.dart:29:10) E/flutter (24807): #7 loginUser (package:ddictor/utils/api.dart:23:16)
post method inside network_util file
`
Future post(String url, {Map headers, body, encoding}) {
return http
.post(url, body: body, headers, encoding: encoding)
.then((http.Response response) {
final String res = response.body;
final int statusCode = response.statusCode;
if (statusCode < 200 || statusCode > 400 || json == null) {
throw new Exception("Error while fetching data");
}
return _decoder.convert(res);
});
}
The errors Failed host lookup: 'api.xyz.com'
and OS Error: No address associated with hostname
usually mean that your DNS lookup fails.
As hinted by OS Error
this is usually a system-level error and nothing specific to http
or Dart.
To diagnose this on your system you can try check e.g. your browser can DNS resolve the host in question. And/or if you’re on a Mac/Linux system you might be able to run dig api.xyz.com
to see if that resolves.
When doing anything network, or I/O in general, it’s a good idea to program very defensively and assume the I/O can sporadically fail or time out.
You can try see if you can make your code degrade more gracefully in cases when e.g. DNS isn’t working as expected.
I’ll go ahead and close this issue since I don’t think there’s anything to be done in http
Anyone facing this issue: try adding <uses-permission android:name="android.permission.INTERNET" />
to your AndroidManifest.xml.
haan78 reacted with thumbs down emoji
rocboronat, feharaujo, saddem123, overdrowe, lucasdelavrapinto, dungnguyentri3110, Kristijan6690, and manishdbcoditation reacted with laugh emoji
dblokhin, Mahmoud2B, rknell, RaviDhakad, SamnangLaor, januwA, DakTop, KareemMohamed21794, rocboronat, RenatoAWK, and 10 more reacted with hooray emoji
SamnangLaor, rocboronat, saddem123, Saviollage, overdrowe, chrystoffer, TinasheKeith, Ringtved, rovannlinhalis, lucasdelavrapinto, and 2 more reacted with heart emoji
rocboronat, pablorgarrido, saddem123, Lambertn33, lucasdelavrapinto, Kristijan6690, JhonaMath, seqwait, ajitbhattarai, and Priananda620 reacted with rocket emoji
rocboronat, shlima, saddem123, lucasdelavrapinto, and Kristijan6690 reacted with eyes emoji
thank you, this worked for me
This was referenced
Mar 28, 2019
I had the same error. In my case it was because the emulator of the phone that I am using does not have access to the internet.
Run the application on a physical mobile device and it worked immediately.
Solution connect the emulator to the internet.
brdacon1 reacted with thumbs down emoji
DaveatCor, dagar07, AbdullahAli1993, thealexanton, DaviCrisostomo, thisisddzin, dsouzajaison, Abdelrhman-Os, aloev, saymo23, and goj1 reacted with hooray emoji
ziyadsfaxi and merinode reacted with rocket emoji
I think we need to add message that you need to add internet permission in Install section of doc
I think we need to add message that you need to add internet permission in Install section of doc
Please +1 and follow https://github.com/flutter/flutter/issues/29688
If we have some flutter docs to point to from this README we can do that.
I have the same issue when run in release mode,but it is ok when debug mode !
@Derkin — please raise the issue at flutter/flutter#29688
This isn’t a problem that can be solved in this package.
Hi,
This error is because if your Simulator or Your phone doesn’t connect to the Internet.
Anyone facing this issue: try adding
<uses-permission android:name="android.permission.INTERNET" />
to your AndroidManifest.xml.
@gurgenDP pls help me this way dont solve my problem
flutter/flutter/#43357
Just ran into this issue. After about half an hour I finally figured out that it was because I had my VPN on..
I have the same issue when run in release mode,but it is ok when debug mode !
i have same issue with my app . So have u figured it out now???
@jawale204 — please raise the issue at flutter/flutter#29688
This isn’t a problem that can be solved in this package.
I have the same issue when run in release mode,but it is ok when debug mode !
i have same issue with my app . So have u figured it out now???
This error is because if your Simulator or Your phone doesn’t connect to the Internet.
I made new minor sdk updates, upgraded the http package, closed the emulator and re-opened it, and stopped the application and re-compiled the problem was fixed.
The errors
Failed host lookup: 'api.xyz.com'
andOS Error: No address associated with hostname
usually mean that your DNS lookup fails.
As hinted byOS Error
this is usually a system-level error and nothing specific tohttp
or Dart.To diagnose this on your system you can try check e.g. your browser can DNS resolve the host in question. And/or if you’re on a Mac/Linux system you might be able to run
dig api.xyz.com
to see if that resolves.When doing anything network, or I/O in general, it’s a good idea to program very defensively and assume the I/O can sporadically fail or time out.
You can try see if you can make your code degrade more gracefully in cases when e.g. DNS isn’t working as expected.I’ll go ahead and close this issue since I don’t think there’s anything to be done in
http
that was valuable insight, thanks @cskau-g man. I was worried about this issue.
It was DNS, I was messing with my DNS settings.
people kept spamming about the missing Internet Permission. That wasn’t my case.
It was hard to find this info. I’ll set the DNS to default settings and see if it’s resolved.
thanks again! 👍🤝
I had the same error. In my case it was because the emulator of the phone that I am using does not have access to the internet.
Run the application on a physical mobile device and it worked immediately.
Solution connect the emulator to the internet.
This solved the issue for me. Thanks a lot!
@jawale204 — please raise the issue at flutter/flutter#29688
This isn’t a problem that can be solved in this package.
step 1
add
to you androidmanifest, if done,
step 2
connect your emulator to a internet, if you cant use in on your physical device
Anyone facing this issue: try adding
<uses-permission android:name="android.permission.INTERNET" />
to your AndroidManifest.xml.
HAVE TRIED THE ABOVE BUT THE SAME ERROR EXISTS PLS HELP….
I am also facing the same error after doing all the steps mentioned above. Please suggest.
Failed Host Lookup error occurs when their is no internet connection in the AVD in the laptop…… Suggestion is to close the AVD, check your internet connection and then open your AVD and then run again……
Also if their is a problem in the API itself the. This error might occur……….
That’s how I did solve it…
I had this issue and the cause of this error for me was that my phone was not connected to the internet 🤦♂️
I’ve faced this issue after trying to build my flutter apk for the first time, with the intention to test it on a real android device.
After building, the issue occurred on both devices (real and emulator).
- There are a couple of AndroidManifest.xml in my project, and they all contain
<uses-permission android:name="android.permission.INTERNET" />
. - Both real device and emulator phones were connected to the internet so that wasn’t the problem.
What helped was reinstalling the http package.
Just ran into this issue. After about half an hour I finally figured out that it was because I had my VPN on..
Thanks you are my hero! same issue hehe
my problem was with the api url it was inccorect.
In my real android device, it is NOT working with Jio internet. With airtel and other networks, it’s working fine. Do telecom operators put proxy etc. in the http requests?
In my real android device, it is NOT working with Jio internet. With airtel and other networks, it’s working fine. Do telecom operators put proxy etc. in the http requests?
For our app users using Jio network this issue happens some times. On same device it works some time, and does not work some time. Server has ipv4-only ip. Only A record is set on DNS server.
In my real android device, it is NOT working with Jio internet. With airtel and other networks, it’s working fine. Do telecom operators put proxy etc. in the http requests?
For our app users using Jio network this issue happens some times. On same device it works some time, and does not work some time. Server has ipv4-only ip. Only A record is set on DNS server.
I solved it by changing api url. Jio uses some SNI url filtering mechanism.
https://cis-india.org/internet-governance/blog/reliance-jio-is-using-sni-inspection-to-block-websites .
So for some reason my previous api endpoint was not being hit.
Hi, yes its correct, thank you
This error is because if your Simulator or Your phone doesn’t connect to the Internet.
Just ran into this issue. After about half an hour I finally figured out that it was because I had my VPN on..
Yes. I have same problem. When i turn VPN ON i have failed host lookup, but internet is working in browser. My requests is not, how can i fix it? I really need work with VPN
i tried every thing , nothing work !!
The «Unable to resolve host» error occurs when Retrofit2 & OkHttp3 are unable to resolve the hostname specified in the API endpoint URL. This can happen due to a variety of reasons, such as incorrect URL, network connectivity issues, or incorrect DNS settings. In this article, we will discuss several methods to fix this error and successfully establish a connection to the API endpoint.
Method 1: Verify API Endpoint URL
If you are facing the error «Unable to resolve host <host-name>: No address associated with hostname» while using Retrofit2 and OkHttp3 in your Android application, it means that the URL you are trying to access is not valid or cannot be resolved. One way to solve this problem is by verifying the API endpoint URL. Here’s how you can do it:
Step 1: Create an instance of your Retrofit client and set the base URL to the API endpoint URL you are trying to access.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
Step 2: Create an interface that defines the API endpoints you want to access. Use the base URL you set in step 1 as the relative URL for each endpoint.
public interface MyApiService {
@GET("users/{id}")
Call<User> getUser(@Path("id") int userId);
}
Step 3: Use the retrofit.create()
method to create an instance of your API service interface.
MyApiService apiService = retrofit.create(MyApiService.class);
Step 4: Call one of the API endpoints defined in your interface using the apiService
instance you created in step 3.
Call<User> call = apiService.getUser(1);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
// Handle successful response
}
@Override
public void onFailure(Call<User> call, Throwable t) {
// Handle failed response
}
});
By following these steps, you can verify the API endpoint URL and ensure that it is valid and can be resolved. If the error persists, you may need to check your network connection or DNS settings.
Method 2: Check Network Connectivity
If you are getting the «Unable to resolve host» error with Retrofit2 and OkHttp3 in Android, it means that the hostname you are trying to connect to is not resolving to an IP address. This can happen due to various reasons, such as network connectivity issues or DNS problems. In this tutorial, we will show you how to fix this error by checking the network connectivity before making the network request.
Step 1: Add Network Permission to Manifest
Before we start, make sure you have added the following network permission to your AndroidManifest.xml file:
<uses-permission android:name="android.permission.INTERNET" />
Step 2: Check Network Connectivity
To check the network connectivity, we will use the ConnectivityManager class. This class provides information about the current network state, such as whether the device is connected to the internet or not. Here is an example code to check the network connectivity:
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnected();
}
This method returns a boolean value indicating whether the device is connected to the internet or not.
Step 3: Make Network Request
Now that we have checked the network connectivity, we can make the network request using Retrofit2 and OkHttp3. Here is an example code to make a GET request:
private void makeNetworkRequest() {
if (isNetworkConnected()) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService apiService = retrofit.create(ApiService.class);
Call<ApiResponse> call = apiService.getData();
call.enqueue(new Callback<ApiResponse>() {
@Override
public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
if (response.isSuccessful()) {
// Handle success response
} else {
// Handle error response
}
}
@Override
public void onFailure(Call<ApiResponse> call, Throwable t) {
// Handle network failure
}
});
} else {
// Handle no network connectivity
}
}
In this example, we first check the network connectivity using the isNetworkConnected()
method. If the device is connected to the internet, we create a Retrofit instance with the base URL and Gson converter factory. We then create an instance of our API service interface and make the network request using the getData()
method. Finally, we handle the response and error using the onResponse()
and onFailure()
methods respectively.
Method 3: Update DNS Settings
To fix the error «Unable to resolve host: No address associated with hostname» with Retrofit2 and OkHttp3 in Android, you can update the DNS settings of your device. Here are the steps to do it:
- Open the Settings app on your Android device.
- Scroll down and tap on «Network & internet».
- Tap on «Advanced» at the bottom of the screen.
- Tap on «Private DNS».
- Select the option «Private DNS provider hostname».
- Enter the DNS server address you want to use. For example, you can use «8.8.8.8» for Google’s DNS server.
- Tap on «Save».
After updating the DNS settings, you can test your Retrofit2 and OkHttp3 code to see if the error is resolved. Here is an example code snippet that shows how to use Retrofit2 and OkHttp3 to make a network request:
val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.client(OkHttpClient.Builder().build())
.addConverterFactory(GsonConverterFactory.create())
.build()
val api = retrofit.create(ApiService::class.java)
api.getData().enqueue(object : Callback<DataResponse> {
override fun onResponse(call: Call<DataResponse>, response: Response<DataResponse>) {
// Handle success response
}
override fun onFailure(call: Call<DataResponse>, t: Throwable) {
// Handle error response
}
})
In this example, ApiService
is an interface that defines the API endpoints, DataResponse
is the data model for the API response, and getData()
is a method in the ApiService
interface that makes a network request using Retrofit2 and OkHttp3.
By following the steps to update the DNS settings and using the example code snippet, you should be able to fix the error «Unable to resolve host: No address associated with hostname» with Retrofit2 and OkHttp3 in Android.
Method 4: Use IP Address instead of Hostname
If you are facing the error «Unable to resolve host <host-name>: No address associated with hostname» with Retrofit2 and OkHttp3, you can try using the IP address instead of the hostname to fix the issue. Here are the steps to do it:
-
Get the IP address of the server you want to connect to. You can use the
ping
command in the terminal or command prompt to get the IP address. -
Replace the hostname with the IP address in the Retrofit2
BaseUrl
annotation. For example:
@BaseUrl("http://192.168.0.1/api/")
- Create a new instance of
OkHttpClient
and set theDns
to use the IP address instead of the hostname. For example:
OkHttpClient client = new OkHttpClient.Builder()
.dns(new Dns() {
@Override
public List<InetAddress> lookup(String hostname) throws UnknownHostException {
if (hostname.equals("your-hostname.com")) {
return Arrays.asList(InetAddress.getByAddress(new byte[]{XXX, XXX, XXX, XXX}));
}
return Dns.SYSTEM.lookup(hostname);
}
})
.build();
Replace your-hostname.com
with the actual hostname and XXX
with the IP address octets.
- Use the new
OkHttpClient
instance with the Retrofit2Builder
. For example:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://your-hostname.com/api/")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
That’s it! Now you should be able to connect to the server using the IP address instead of the hostname.
Note: This solution is only recommended if you cannot fix the DNS resolution issue on your network. Using the IP address directly may cause issues if the IP address changes or if the server has multiple IP addresses.