Android How to check URL name or IP is rechable - android

My code is as follow:
public chkRechable(String hostNameOrIp) {
boolean isRechable = InetAddress.getByName(hostNameOrIp).isReachable(30);
return isRechable;
}
Parameter can be "http://192.168.0.77:8080/ws/api/customer/5" or "http://example.com:8080/ws/api/customer/5"
But everytime it's returning false although I can browse the URL.

What do you mean "reachable"?
If "open the page" means "reachable", you can just try to use an HTTP connection to connect to it. If you got exceptions: your net work might down; you cannot connect to the host;
Then you shall check the http return code, to see if there are 404 or other errors.

Related

Unable to return IP address using react-native-device-info's getIPAddress()

I need to return the IP address for the device running my React Native app (an Android smart tv app). I am making use of react-native-device-info which has allowed me to get the model, manufacturer and operating system. However I am unable to get the ip address.
This is my code
deviceInfo = DeviceInfo.getIPAddress().then(ip => {
return ip;
});
However on the front end it appears as [object Object]. I can see in the console it is returning an object like this:
wifi:
_40: 0
_55: null
_65: 0
_72: null
I would have hoped to just return a string of the correct IP address.
I have also added the right permissions in my AndroidManifest.xml.
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Also worth noting I am passing the information back by value: ${JSON.stringify(deviceInfo)}
Any one experienced this issue before?
I have used below library:
https://www.npmjs.com/package/react-native-network-info
And it is working fine, Below is the code:
// Get IPv4 IP (priority: WiFi first, cellular second)
NetworkInfo.getIPV4Address().then(ipv4Address => {
console.log(ipv4Address); //result e.g 192.168.1.100
});
Since its returning a promise try putting inside a async function and try to get the result.
Ex:
const getIpAddress = async()=>{
const ip = await DeviceInfo.getIPAddress();
console.log(ip);
return ip;
}
Hope it helps. Thank you.

failed to connect to localhost/127.0.0.1 android

I am new to android development, and trying to call local .NET web api service in android via retrofit library. After starting my web api on IIS I am getting this error failed to connect to localhost/127.0.0.1 android.
When I did same thing as suggested http://themakeinfo.com/2015/04/retrofit-android-tutorial/, It's working fine, But my localhost service is not calling up from android
My service url is,
http://localhost:52511/api/Values/getAllStudents/5
and it is giving me output in XML format in browser too.
I have also try to call it with,
public interface gitapi {
#GET("/api/Values/GetProduct/{id}") //here is the other url part.best way is to start using /
public void getFeed(#Path("id") int id, Callback<gitmodel> response);
}
public class gitmodel {
public int studentId;
public String studentName;
public String studentAddress;
}
String API = "http://10.0.2.2:52511";
public void CallService(View view){
RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(API).build();
gitapi git = restAdapter.create(gitapi.class);
int id = 5;
git.getFeed(id, new Callback<gitmodel>() {
#Override
public void success(gitmodel gitmodel, Response response) {
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_LONG).show();
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(getApplicationContext(), "Errors", Toast.LENGTH_LONG).show();
}
});
}
but no luck.
Please tell me where do I need to change to make it work. ?
Response I am getting in browser is,
<ArrayOfstudents xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/APICall.Controllers">
<students>
<studentAddress>valsad</studentAddress>
<studentId>1</studentId>
<studentName>Keval</studentName>
</students>
<students>
<studentAddress>Hyderabad</studentAddress>
<studentId>2</studentId>
<studentName>Honey</studentName>
</students>
</ArrayOfstudents>
Instead of using 127.0.0.1:<PORT> use your local IP
There's nothing to do with retrofit library in your case.
It's about your network settings,
your phone and IIS server must be the same LAN.
You can follow as below.
Launch an AP on you IIS server;
Connecting the AP with your phone.
Sometimes you need to close security firewall on your IIS server.
I had the same problem as u (failed to connect to localhost/127.0.0.1).
First of all i recommend u to read this:
android developer's guide (main part of this on the image↓)
I had all of this, mean A, B and C. As C(emulator) i used a Genymotion.
And i solved my problem by changing Network Configurations on it.
IMPORTANT: my adress in baseURL were: "localhost:8099/"
Let's see it:
U should click on Settings → Network → check Use HTTP Proxy → input your IP adress and Port(in my situation it was 8099) → close. See it more details on image ↓
I have the same problem, and I resolve it by changing the IP address instead of 'localhost':
open cmd(if you are using windows): type 'ipconfig' and see your computer's ip.(make sure that your computer and your android device connect to the same network).
remove 'localhost' in the url and use the ip(ip of your computer in step 1).
run the project again and check
Actually this helped when using 2 apps on the same Android device (Android 9)
android:usesCleartextTraffic="true"
You can try this in androidmanifest.xml
android:usesCleartextTraffic="true"

How put the correct "url" for a getConnection with DriverManager?

I am trying to connect to a MySQL database in an Android application but am unable to do so.
The URL I'm using for the connection to a MySQL database is: jdbc:mysql://xx.xx.x.xxx/dbname, where xx.xx.x.xxx represents the IP address of my server. The database dbname is managed by phpMyAdmin on this server.
But I always receive the same error : com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
I have the internet PERMISSION in my manifest.
The code I'm using:
private void callSQL() {
java.sql.Connection laConnection;
java.sql.Statement transmission;
ResultSet leResultat;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
laConnection= DriverManager.getConnection("jdbc:mysql://xx.xx.x.xxx/dbname", "user", "passwrd");
transmission = laConnection.createStatement();
leResultat= transmission.executeQuery("select * from Communes");
while (leResultat.next()) {
System.out.println("Commune : "+ leResultat.getString("Nom"));
}
}catch(Exception e){
System.out.println(e);
}
}
I have been able to use another solution with a HTTP request on a PHP page that connects to the database. This solution works well, but which one is the best way to use?
I found the solution. The problem wasn't the code. The problem is the connection. I hadn't the permission to connect the database. With the permission allowed to a distant user on the database, it was OK.

getjson response returns null in phonegap (android)

$.getJSON("http://localhost:8080/v1/message",
function(data) {
console.log(data);
alert("message"+data);//this alert stmt is displayed it means that
the service call is getting executed
});
service method
#RequestMapping(method = RequestMethod.GET,
value = "/message" )
#ResponseStatus(HttpStatus.OK)
#ResponseBody
public String message()
{
return "jasdknsd";
}
I am getting response of this call as null please help me out if I am doing something wrong in the service method and I have both of them in same network because of which I am not using callback
Connection to localhost is not supported.
http://code.google.com/p/android/issues/detail?id=133
127.0.0.1 is the emulated system's own loopback interface, not the one running on
your host development machine.
within the Android system, one should use 10.0.2.2 which is an alias specifically
setup to contact your host 127.0.0.1
use 10.0.2.2 instead of localhost:8080

getInputStream throws Exception

I'm trying to invoke a webservice and parse the returned XML, so my invoke URL is :
http://192.168.1.12/cr.ws/CarCategories.asmx/CarCategoryComparatorRQ?IdUser=1076&IdCurrency=1&IdLanguage=1&IdCarCategory=0&IdPickupRentCarAgencies=3&IdReturnRentCarAgencies=3&PickupDate=6/4/2011&ReturnDate=9/4/2011&Supplier=Prima%20Rent%20a%20Car&b=prima
in my browser I get the desired response :
<CarCategoryComparatorRS>
<CarCategory>
<IdCar>22</IdCar>
<IdCarCategory>22</IdCarCategory>
<Supplier>AvantGarde Rent a Car</Supplier>
<PickupRentCarAgencies>Tunis; Aéroport de Tunis-Carthage</PickupRentCarAgencies>
<IdPickupRentCarAgencies>5</IdPickupRentCarAgencies>
<ReturnRentCarAgencies>Tunis; Aéroport de Tunis-Carthage</ReturnRentCarAgencies>
<IdReturnRentCarAgencies>5</IdReturnRentCarAgencies>
<IdUser>705</IdUser>
<Title>Catégorie A [ex:Kia Rio;Renault Symbol]</Title>
<IdCurrency>1</IdCurrency>
<ImageUrl>Car-22-20090521-125545.jpg</ImageUrl>
<MemberReductionValue>0</MemberReductionValue>
<Rate>150</Rate>
<DelayRate>0</DelayRate>
<ReductionValue>135</ReductionValue>
<DayRate>45</DayRate>
<Reduction>10%</Reduction>
<AccompteValue>67.500</AccompteValue>
<Accompte>50</Accompte>
<TotalRate>0000135000</TotalRate>
</CarCategory>
</CarCategoryComparatorRS>
But this function trows java.io.FileNotFoundException
protected InputStream getInputStream() {
try {
return feedUrl.openConnection().getInputStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
Please help me, I wasted couple hours searching but nothing :(
Thanks.
The error is caused by the spaces in this param :"Supplier=Prima Rent a Car", so i replaced this param by UrlEncoder.encode("Supplier=Prima Rent a Car") and it worked.
If you type that URL in your device's browser address bar do you get anything?
It looks like you are trying to request an address on a local machine or LAN. Are you requesting this on the android device? My guess is you need to run your server on the machine on a different interface or open up connections to the required port.
I think your url is being interpreted as a file url.
What about logging your url before you call openConnection as a sanity check:
Log.e("MyApp", feedUrl);
On second thought, could you post the logcat output? I'm skeptical as to how your code could ever throw a FileNotFoundException.

Categories

Resources