Connecting localhost via android - Connection to 10.0.2.2 refused - android

I have an apache server installed in my PC where I host one PHP file.
Then I tried to connect to that file using eclipse, but it always gives me below error
connection to http://10.0.2.2:8080 refused.
I tried changing address to the followings, but got similar error all the time.
http://10.0.2.2
http://127.0.0.1
http://localhost
Can anyone please help me.
EDITED: Just for information, I can access to remoter server (e.g. www.mydomain.com) without any problem.
CLASS FILE:
HttpClient httpclient = new DefaultHttpClient();
Log.d("test","t0");
HttpPost httppost = new HttpPost("http://10.0.2.2:8080/mylibman/data.php");
Log.d("test","t1");
HttpResponse response = httpclient.execute(httppost); // error here
Log.d("test","t2");
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.migrationdesk.mylibman"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET" />
Error LogCat:
11-16 02:02:20.803: E/log_tag(1427): Error in http connection org.apache.http.conn.HttpHostConnectException: Connection to http://10.0.2.2:8080 refused
11-16 02:02:20.803: E/log_tag(1427): Error converting result java.lang.NullPointerException: lock == null
11-16 02:02:20.803: E/log_tag(1427): Error parsing data org.json.JSONException: End of input at character 0 of

alright go to Apache httpd.conf (located in Apache folder): and search for
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
and check if the second line is Deny, if it is then change it to:
Allow from all
then restart the Appache server, and tell me the feadback.
Edit
try it out in your real device:
go to CMD and type ipconfig under IPv4 take the IP address and change the IP it will look similar to this:
http://192.168.0.106:8080/mylibman/data.php // similar to this.
Turn Off the firewall and any anti-virus application in your PC
and please give me the feedback.

Mike helped me a lot on this issue. So here my steps to avoid this Connection refused.
1) Add if to test Android SDK. It seems that in new versions you have to explicity allow the connection to be open in a different thread:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
System.out.println("*** My thread is now configured to allow connection");
}
...
2) Add an exception for your port:
in your case allow inbound connection for port 8080
3) test your connection by browsing the desired url locally
use your browser and try to visit http://10.0.2.2:8080 locally
4) Add in your manifest file a permission for internet:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yourapp"
android:versionCode="1"
android:versionName="1.1" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET"/>
I am using Wamp, and its apache is listening to servername localhost and port 8080 (allow from all in httpd.conf).
My local IP is something similar to 192.168.0.XXX/folder/my-page-here

You can use your real IP address to reach your virtual server. Take a look at my answer here. I hope it helps.

if your SDK version is less then 9 then add above code for SDK version them some changes in Apache update httpd.conf as line deny from all..replace that sentence Allow from all and restart services of WAMP server then use 10.0.2.2 address or 10.0.2.2:8080 port no and include permission line in android AndroidManifest file
<uses-permission
android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE">
</uses-permission>

I fix this problem by writing my IP address from cmd -> ipconfig in the url :
HttpPost httppost = new HttpPost( "http://192.168.x.x/mylibman/data.php" );

Related

Network Error on API requests on Expo Android

I am developing a React Native app using Expo and I recently ran into a weird issue. API requests don't work on Android devices however they're totally fine on iOS. The server I'm trying to connect to isn't localhost. I tried to use axios and fetch, both result in Network Error and the server doesn't receive a request. I also made requests to open APIs which got me the same error, so I believe the problem isn't on the server's side.
Here's the code of the request:
const axiosInstance = axios.create({
timeout: 120000,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
}
})
const res = await axiosInstance.post(`${serverHostApi}/merchant/login`, payload)
Here's the stack trace:
Network Error
- node_modules\axios\lib\helpers\normalizeHeaderName.js:8:14 in processHeader
* http://192.168.150.71:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:226876:26 in handleError
- node_modules\event-target-shim\dist\event-target-shim.js:818:20 in EventTarget.prototype.dispatchEvent
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:575:10 in setReadyState
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:389:6 in __didCompleteResponse
- node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:189:10 in emit
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:425:19 in __callFunction
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112:6 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:373:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:111:4 in callFunctionReturnFlushedQueue
* [native code]:null in callFunctionReturnFlushedQueue
I'm using Expo 38.0.0, React Native SDK 38.0.2.
Any help would be highly appreciated!
If this is happening only in the android app. It might be a case you accidently removed internet permission from your android app. Kindly check you have proper permission in the Android Manifest File.
To Check , go the YourApp/android/app/src/main and open AndroidManifest.xml
and check if you have this line
<uses-permission android:name="android.permission.INTERNET" />
if you don't have it , add this line inside your Manifest file like this
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
I also ran into this problem.
You can use tools like SSL Labs to test the validity of your SSL certificate.
SSL SERVER TEST
I solved it with this method
Only way that I found to resolve is downgrade the version. Or you should make sure that TLS 1.0 and TLS 1.1 is disabled on the server.
"axios": "0.24.0"

Cannot connect to Apollo GraphQL server on Android Release [react native]

httpURI = 'http://17.25.16.68:4000/graphql' //example
const httpLink = createHttpLink({ uri: httpURI });
const client = new ApolloClient({ link:httpLink, cache: new InMemoryCache() });
The connection works on debug mode, but when I run it on release, no connection is made.
Do I need to enable outgoing connections somewhere in the Android release config?
This is something that worked for me. apparently android pie doesn't allow network requests to URLs without https.
<application
...
android:usesCleartextTraffic="true"
...>
...
</application>
This file allowed android for reaching http requests.
In android/app/src/main/AndroidManifest.xml add the line below
<application
.
.
.
android:usesCleartextTraffic="true"
.
.
.
>
</application>

I want to communicate with kernel to set up SADB in Android NDK but getting Permission Denied Error

I am using following code and getting permission denied error.
if ((mSockFd = socket(PF_KEY, SOCK_RAW, PF_KEY_V2)) < 0) {
LOGE("IPSec Init : PF_KEY socket creation failed");
LOGE("mSockFd : %d, Error no : %d",mSockFd,errno);
LOGE("Error String : %s",strerror(errno));
}
I have added following permission in AndroidMenifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Please help me solve this problem.
Where
PF_KEY is a new socket protocol family used by trusted privileged
key management applications to communicate with an operating
system's key management internals
To open SOCK_RAW type socket you need to have root privileges. If you are trying to run this on Mobile then phone must be rooted. Or try to implement in Linux Machine you will get root privilege easily.

Webview Localhost Connection refused using 10.0.2.2 address

I'm just making a basic Webview app on an android emulator and cannot connect to a website hosted on my computer.
Here is my code:
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.emswebviewer"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET"/>
Main Activity Java file:
public class MainActivity extends Activity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
System.out.println("*** My thread is now configured to allow connection");
}
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
webView.loadUrl("http://10.0.2.2:8080");
}
Terminal (Starting website on local host port 8080):
Michaels-MacBook-Pro-5:web michael$ php -S localhost:8080
PHP 5.5.14 Development Server started at Mon Dec 22 14:08:01 2014
Listening on http://localhost:8080
httpd.conf File (Under Apache Folder):
#
# This should be changed to whatever you set DocumentRoot to.
#
<Directory "/Applications/MAMP/htdocs">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
Options All
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride All
#
# Controls who can get stuff from this server.
#
Order allow,deny
Allow from all
I am using Mamp and AVD as the emulator.
When I run my app, it returns net::ERR_CONNECTION_REFUSED on the Main activity page.
Do I need to allow external connections somewhere? OR is there something inherently wrong with what I am trying to do?
localhost on your emulator it's not localhost on your desktop. On your desktop you need to run php server with php -S 10.0.2.2:8080 (if that it's your IP). And than access that IP from the emulator with WebView at your app. You can't access desktop's localhost from the emulator (no directly at least). Don't start your server on localhost only.
Look for this file ports.conf and add Listen 8080 if necessary and restart the server.
Using 10.0.2.2 is correct and not wrong in anyway as such. You can see why in the below answer
why do we use 10.0.2.2 to connect to local web server instead of using computer ip address in android client
The issue may be related to your application listening to 127.0.0.1 only and not all interfaces. You need to make sure you use something like below
php -S 0.0.0.0:8080
I saw your bounty question as well, which also answers that you need run your Django server as below
python manage.py runserver 0.0.0.0:8000
PS: And next time your post a bounty #kingraphaII, be kind enough to respond to people and don't just be a ghost
What worked for me was to replace localhost address with my pc laptop, 192.168.2.7, in my case. #gorlok comment helped me towards my solution.
Android Emulator is a separate device. Emulator isn't part You Computer. Emulator cann't access your Local Server.
So Emulator return net::ERR_CONNECTION_REFUSED error.
I found a Simpal way to solve the issue.
Get my local IP address as like 192.168.99.112
To get your IP address open your Tarminal/cmd type ipconfig
Ensure your internet permission in AndroidManifest File
<uses-permission android:name="android.permission.INTERNET"/>
Then
WebView browser = (WebView)findViewById(R.id.webview);
webView.loadUrl("http://192.168.99.112/projectName");

How can i connect to sql server from my android application?

I'm developing an android application. I need connect to sql server. I wrote a code for test connection but i get this error :
java.sql.SQLException: Network error IOException: Permission denied
I checked connection string.
I closed firewall for 1433.
I tried configured Sql Server tcp and remote access settings
but i still get the same error. What is my mistake?
My environment:
Sql Server 2008 R2
Eclipse
jtds
My Code is:
try
{
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
**Connection conn=DriverManager.getConnection("jdbc:jtds:sqlserver://192.168.1.33:1433/Android_Deneme;instance=CASPER\\MORTY;user=ugur;password=1234");**
String sql="insert into tablo1(ad,yas) values(?,?)";
PreparedStatement prepared = conn.prepareStatement(sql);
prepared.setString(1, "ali");
prepared.setInt(2, 30);
prepared.executeUpdate();
}
catch(Exception e)
{
e.printStackTrace();
}
You have to add the following permission to your application manifest file.
<manifest>
.....
<uses-permission android:name="android.permission.INTERNET" />
.....
</manifest>

Categories

Resources