Android HTTP Connection - java

Can anybody tell my why this doesn't work in the Android emulator? From the browser I have access and the server is internal. All I can think of is that I'm missing some configuration on my app so it can access the network layer.
try {
InetAddress server = Inet4Address.getByName("thehost");
//Doesn't work either
//or InetAddress server2 = Inet4Address.getByAddress(new String("192.168.1.30").getBytes());
if(server.isReachable(5000)){
Log.d(TAG, "Ping!");
}
Socket clientsocket = new Socket(server, 8080);
} catch (UnknownHostException e) {
Log.e(TAG, "Server Not Found");
} catch (IOException e) {
Log.e(TAG, "Couldn't open socket");
}
Throws an UnknownHostException
Thanks

As far as configuration goes, the only setting you should need to access the Internet from your application is the INTERNET permission, enabled by adding the following line outside the Application tags within your application Manifest.
<uses-permission android:name="android.permission.INTERNET" />
So the manifest would follow this general construction
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.android.apis">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name="MyApplication"
android:label="#string/application_title"
android:icon="#drawable/my_icon">
[ .. Your Activities go here ]
</application>
</manifest>

It might still not work, because of the timeout. Since you need root permissions to send an ICMP Package and the implemetation of isReachable will use the slow TCP version of ECHO. Chekcout the javaDoc.

Related

executing Socket(hostname,port) causes android to crash [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 5 years ago.
Help! I'm trying to do some simple java socket networking in Android Studio and I can't even get in the door. The server program seems to be working ok but the android app client crashes with the error "Unfortunately InTouch has stopped" while executing the line:
sock = new Socket("Mark2015jun08", 4415);
where the hostname I put in is what is reported by the C:>hostname command, the windows Networking Control Panel and it shows up in the DHCP table when I log into the router. It even crashes when I put in "" for a hostname which the documentation says should open a loopback. I've tried calling Socket() a dozen different ways as you can see from my code below. I could sure use some help.
Thanks, -Mark
In the android client program I put the following try statement in the onResume() method:
try {
//sock = new Socket("Mark2015jun08", 4415);
byte[] ip = {(byte)192, (byte)168, (byte)1, (byte)124};
//sock = new Socket(InetAddress.getByAddress(ip), 4415);
//sock = new Socket(InetAddress.getByName("192.168.1.124"), 4415);
//sock = new Socket("LOCALHOST", 4415);
sock = new Socket("", 4415);
// ommitted logic to set socket timeout and
// open object streams based on sock
} catch (IOException e){
sock = null;
log(e.toString());
}
Both Windows ipconfig and the router DHCP table both confirm my ip address but I still get the same error. Three different sources all agree on my hostname but no matter what string I put in for hostname, even "", it doesn't work. What am I doing wrong?
I use the following permissions in my Manifest.xml file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
This is my server program below created in Netbeans and I run it from the Windows cmd.exe window with the command C:>java -jar intouchserver.jar. This runs the server program on the laptop and it gets to the line
sock = serversock.accept();
and stops exactly as the documentation for accept() explains. As far as I can tell it's listening to port 4415. (Note: I checked serversock before this statement: it is non-null.)
package intouchserver;
import ...
public class InTouchServer {
private static ServerSocket serversock;
private static Socket sock;
public static void main(String[] args) {
try {
serversock = new ServerSocket(4415);
sock = serversock.accept();
} catch (IOException e){
System.out.println("Can't establish socket");
System.out.println(e);
System.exit(1);
}
// ommitted logic to open object streams based on sock
// and read and write to them
}
}
I solved my own problem. It turns out that if the Socket() call is in the onResume() function where I put it then you get a fairly useless error message but if you put the Socket() command in the onCreate() function you get a much more informative error: namely "NETWORK ON THE MAIN THREAD". So then putting the Socket() call in a thread solved the problem and off I went. THANK YOU so much James K Polk for the tip on logcat. I've been struggling with those "Application has Stopped" messages all along.

ParseObjects from Android App not created on Parse Server

I have deployed Parse Server on Heroku. The Mongo Lab and setup and everything is working fine. The server is successfully deployed on the parse server but I am not able to connect my android app to the parse server deployed on heroku.
I have configured the below details in my parse server index.js
var api = new ParseServer({
serverURL: "https://parseservertest12.herokuapp.com",
databaseURI: databaseUri || 'mongodb://heroku_jhwmv6c9:khhmh38a4u95krh1gbajni59rs#ds021034.mlab.com:21034/heroku_jhwmv6c9',
cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
appId: process.env.APP_ID || 'myAppId',
masterKey: process.env.MASTER_KEY || 'myMasterKey' //Add your master key here. Keep it secret!
});
Check my Heroku Creditentials
Here is my Application.java Class
Parse.initialize(new Parse.Configuration.Builder(getApplicationContext())
.applicationId("myAppId")
.clientKey("myMasterKey")
.server("https://parseservertest12.herokuapp.com/parse")
.build()
);
ParseObject gameScore = new ParseObject("GameScore");
gameScore.put("score", 1337);
gameScore.put("playerName", "Sean Plott");
gameScore.put("cheatMode", false);
gameScore.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
Log.i("Parse", "Save Succeeded");
} else {
Log.i("Parse", "Save Failed");
}
}
});
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
// Optionally enable public read access.
// defaultACL.setPublicReadAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
}
This is my AndroidManifest.xml
<application
android:name=".StarterApplication"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.parse.APPLICATION_ID"
android:value="#string/parse_app_id" />
<meta-data
android:name="com.parse.CLIENT_KEY"
android:value="#string/parse_client_key" />
This is the Strings.xml
<string name="parse_app_id">myAppId</string>
<string name="parse_client_key">myMasterKey</string>
I have tried resolving this issue a lot of times and referred to many online solutions but my method and everything seems correct but I am still not able to connect the android application to my parse server. My application is ready on the Android device but connecting to the parse server has caused me alot of delay please help me resolve this issue.
Running parse server with the VERBOSE=1 environment variable will help you debug this issue.
Also, can you try replacing your serverURL with https://parseservertest12.herokuapp.com/parse/ (adding a trailing /). In the android app.

Android API 23 java.net.UnknownHostException: Unable to resolve host "URL": No address associated with hostname

Im facing a big problem, Im trying to connect to an URL using a GET method. It give me an error java.net.UnknownHostException: Unable to resolve host "URL": No address associated with hostname.
I have been reading some post and all people say it is about permissions.My permissions are:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
I can access to that URL by using chrome in my mobile, it means that wifi is working.
I am using a Motorola g 2, API 23.
Printing the response on the Log ?
Did you try switching of the WiFi or phone or both and tried again ?
This problem can occur when you are on VPN. I had a similar issue. After disconnecting from the VPN I tried connecting again. It got connected.
Also try rechecking the URL since the UnknownHostException is popping up there is high possibility that the URL string you are passing in the program(URL class probably) is wrong.
Hope it helps.
You have two solutions for your problem. The quick one is to lower targetApi to 22 (build.gradle file). Second is to use the new runtimePermission model:
Since your target api is 23 you should add the permissions on runtime too.
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.INTERNET) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(
Manifest.permission.INTERNET)) {
// Explain to the user why we need to read the contacts
}
requestPermissions(new String[]{Manifest.permission.INTERNET},
MY_PERMISSIONS_REQUEST_INTERNET);
// MY_PERMISSIONS_REQUEST_INTERNET is an
// app-defined int constant
return;
}
Sniplet found here: https://developer.android.com/preview/features/runtime-permissions.html

Android browser can't connect to local nanohttpd service

I'm creating a service as root using WakefulBroadcastReceiver approach for some test purpose (Note that I just tested with an Activity launching the server, same thing happen):
MyService.java
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "Server starting");
// Create the server
server = new WebServer(6666);
new Thread(new Runnable() {
#Override
public void run() {
try {
server.start();
} catch (IOException e) {
Log.d(TAG, e.getMessage());
}
}
}).start();
...
return START_STICKY;
}
WebServer.java :
public class WebServer extends NanoHTTPD {
#Override
public Response serve(IHTTPSession session) {
Log.d(TAG, "Serving");
return new NanoHTTPD.Response("<html><body>test</body></html>");
}
I push using adb the APK in /system/app so the service can be called without using an activity first. Then restart the shell.
I can see logs of the server waiting for connection and then :
if I use wget http://127.0.0.1:6666 using adb shell I can see the log "Serving".
if I use the device browser with the same address (tried localhost too), the server isn't reached.
I use API18 and default Nexus7 AVD (tried with Genymotion too and a samsung tablet) but nothing works. There is no proxy configured in network settings.
I don't get why browser (on the device) isn't reaching my 6666 port on 127.0.0.1 (on the device too)
Here is the manifest :
<application android:allowBackup="true" android:label="#string/app_name"
android:icon="#mipmap/ic_launcher" android:theme="#style/AppTheme">
<service android:name=".MyService" android:label="Tool" android:enabled="true"/>
<receiver android:name=".receiver.BootCompleteReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I was running crazy and finally someone sent me this link :
https://superuser.com/questions/188058/which-ports-are-considered-unsafe-on-chrome
Port 6666 is considered unsafe ... I wish it would be written on the page instead of couldn't reach server.

Android socket throws UnknownHostException error

Why do I get this error...
java.net.UnknownHostException: http://google.com
...when I do this in my Activity -> onCreate?
try {
Socket socket = new Socket("http://google.com", 80);
} catch(Exception e) {
Log.e(tag, e.toString());
return;
}
And yes, I do have the Internet permission set in my manifest.
<uses-permission android:name="android.permission.INTERNET" />
This is being tested on a physical Nexus S phone
Use www.google.com, without the http:// part.
Is it throwing an UnknownException or UnknownHostException?
UnknownHostException means there is a problem with the hostname lookup. Try it without the "http://" and if that doesn't work, try it with the direct IP address.
Its not your app permissions that is failing, otherwise it would throw a SecurityException.
Socket throws an
UnknownHostException - if the IP address of the host could not be determined.
Do you have Internet Access enabled? Try it with another host or with the IP and/or try restarting your phone.

Categories

Resources