how to get response from php file? - java

I'm currently trying to connect my phpmyadmin server with android studio.
I'm using the emulator if it matters.
I made some php files to receive data and change data in my database.
checkuserexist.php
<?php
require('con1.php');
if (isset($_GET['username'])) {
$username = mysqli_real_escape_string($link,$_GET['username']);
if (!empty($username)) {
$username_query = mysqli_query($link,"SELECT * FROM users WHERE username='".$username."'");
$username_result = mysqli_num_rows($username_query);
if($username_result == 0)
print $existornot = "NotExist";
else print $existornot = "Exist";
}
}
?>
And in my Android Studio program:
URL url = new URL("http://10.0.2.2:8080/fives/checkuserexist.php?username=yariv");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream stream = conn.getInputStream();
InputStreamReader isReader = new InputStreamReader(stream );
//put output stream into a string
BufferedReader br = new BufferedReader(isReader );
String result = "";
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
result += line;
}
br.close();
InputStream stream = conn.getInputStream();
return an exeption:
failed to connect to /10.0.2.2 (port 8080): connect failed: ETIMEDOUT (Connection timed out)
How to solve this exeption?

You could echo out some JSON in the PHP file and use the JSONObject/JSONArray classes in android

should check the emulator network setting to see what is your main machine IP address.
second way :
open run menu, type cmd and again type ipconfig.
you can also try other IP v4 addresses found in the here:

Related

How to get user machine IP using Java

I am trying to get users machine ipAddress using java from my server.
I used the following code, and it works fine in local.
URL url = new URL("http://www.geoplugin.net/json.gp?jsoncallback=?");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
}
Using this class, response shows the ip in my local web app.(localhost:8080/myApp/getIp)
I deployed this war to my AWS server, and tried to run the servlet. But this always shows the AWS ip address only. (myIp:8080/myApp/getIp)
It doesn't shows my machine IP.
What was mistake in my code, can someone assist in this?
ServletRequest.getRemoteAddr() OR
getRemoteHost() and getRemotePort()
should returns details of the actual client
If you wanna get client ip i.e. user accessing your web-app through browser, then you can use (client-side-script)javascript to do so. Below is simple example for the same.
function show(response) {
console.log(response);
var html = 'Something went wrong !';
if (200 == response.geoplugin_status) {
html = 'Got your ip as: ' + response.geoplugin_request;
}
document.getElementById('ip').innerHTML = html;
}
var script = document.createElement('script');
script.async = true;
script.src = 'http://www.geoplugin.net/json.gp?jsoncallback=show';
document.getElementById('ip').appendChild(script);
<div id='ip'>Fetching IP ...</div>

java.io.FileNotFoundException: When using real server

I am beginner in Java and Android Studio. I have written a code by Android Studio and Wamp as server and Genymotion as simulator. all codes work fine and I can interact with mysql by use of my .php files
Then I decide to transfer codes to real server.
but I get this error:
java.io.FileNotFoundException: http://burj.1shahrvand.com/Burj/BikerLogin.php
The File is available check it here but I get Exception that file not found
The code is like this:
String uri = rp.getUri();
if(rp.getMethod().equals("GET")){
uri += "?" + rp.getEncodedParams();
}
HttpURLConnection connection;
try {
URL url = new URL(uri);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(rp.getMethod());
if (rp.getMethod().equals("POST")){
connection.setDoOutput(true);
connection.setDoInput(true);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(rp.getEncodedParams());
writer.flush();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
Log.i("HESAM Original", e.getMessage());
e.printStackTrace();
}
return null;
I appreciate your Help!
You will get a FileNotFoundException if you call getInputStream after the server has responded withe a 404 or 410 status code.
If you want to avoid the exception, check that the response status code is a 2xx code. If it isn't then use getErrorStream instead of getInputStream.
In my case, There is an option in my Cpanel. It is MOD Security, Just turn it off, after 15 minutes my app worked properly.
Simply you need to add the port name(:8080) with the localhost ip address in URL String, like i did:
String login_url = "http://192.168.0.136:8080/login.php";

Getting UnknownHostException instead of SocketTimeOutExcepetion

I am new to android and Java. And I am trying to learn android app development from UDACITY. I was trying to run this code and I am expecting a SocketTimeOutExcepetion but what I am getting is UnknownHostException.
try {
final String BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?";
final String ZIP = "zip";
final String MODE = "mode";
final String UNITS = "units";
final String COUNT = "cnt";
final String APP_ID = "appid";
Uri builtUri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(ZIP, params[0] + ",in")
.appendQueryParameter(MODE,format)
.appendQueryParameter(UNITS, units)
.appendQueryParameter(COUNT, Integer.toString(numDays))
.appendQueryParameter(APP_ID, BuildConfig.OPEN_WEATHER_MAP_API_KEY)
.build();
String str = java.net.URLDecoder.decode(builtUri.toString());
URL url = new URL(str);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null)
buffer.append(line + "/n");
if (buffer.length() == 0)
return null;
forecastJsonStr = buffer.toString();
Log.v(LOG_TAG,"JSON forcast string:" +forecastJsonStr);
}catch(SocketTimeoutException e) {
startActivity(new Intent(getActivity(),CheckNet.class));
} catch (IOException e) {
Log.e("FetchWeatherTask", "Error:" + e.toString());
return null;
}
I tested it on my phone running Android version 4.0.4. And while testing I had my mobile data and wifi off
When your mobile data and wifi are turned off, the socket layer is unable to resolve internet addresses (e.g. "openweathermap.org") into an IP address. This is why you get an UnknownHostException.
Whereas, when you're on a network, and it's able to resolve IP addresses, and the server fails to reply, you will get a SocketTimeoutException.
If you want to simulate the exception do the following:
Disconnect your data and connect your Wi-Fi
Edit your setting of your Wi-Fi connection
Change to static IP and put 169.254.0.50 for IP, 255.255.0.0 for subnet and 169.254.0.1 for gateway
Change the BASE_URL = "192.241.169.168/data/2.5/forecast/daily?"
Run your app

opening connection and reading stream

I get a runtime error when I try to do "http://www.oracle.com". It says, error java.net.UnknnownHostException:www.oracle.com then it lists a whole bunch of errors having to do with Sockets, HttpURLConnection etc. and it all ends up pointing at this connect method, specifically InputStream steam line.
Here is my code:
public void connect (String website) throws IOException {
URL u = new URL(website);
URLConnection conn = u.openConnection();
InputStream stream = conn.getInputStream();
Scanner input = new Scanner(stream);
input.useDelimiter("<a");
readWebsite(input);
}
Try connecting by IP address:
URL u = new URL("http://23.56.70.140");

Desktop client web server communication

I am doing client server communication. I got both connected via URLConnection classes.
Now I am trying to send log in information to server, Server will check if information is correct else it will ask me to log in again and for this scenario lets assume log in was unsuccessful. But after getting response from server when I try again to send log in information I am getting
java.net.ProtocolException: Cannot write output after reading input.
Here is my code:
URL url = new URL(uniRL);
java.net.URLConnection connection = url.openConnection();
connection.setAllowUserInteraction(true);
connection.setDoOutput(true);
while(true){
System.out.println("Enter 1-login , 2-Exit");
useroption = input.nextLine();
numOption = Integer.parseInt(useroption);
if( numOption == 1){
OutputStreamWriter writer = new OutputStreamWriter(
connection.getOutputStream());
user_login = login();
writer.write(user_login[0]+"#");
writer.write(user_login[1]);
writer.flush();
//out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
while ((tempString = in.readLine()) != null) {
decodedString = tempString;
//System.out.println(decodedString);
//System.out.println(decodedString.equalsIgnoreCase("unknown user"));
}
in.close();
if((decodedString.equalsIgnoreCase("unknown user"))){continue;}
else{break;}
}
When you call in.close(), you're actually closing the stream used by the URL connection. You'd need to call url.openConnection() again to re-open the stream...

Categories