I have a working ASP.NET Web API service running in Visual Studio on my dev box. I can easily get the proper results from either I.E. or FireFox by entering: http://localhost:61420/api/products. But when trying to read it from my Android Project using my AVD I get an exception thrown saying:
localhost/127.0.0.1:61420 - Connection refused.
I know my Android Java code works because I can access the WCF RESTFul service running on my Website (the URLthat's currently commented out). My Android code is pasted below.
So, why am I getting the error when accessing from my Eclipse project but not when accessing it from a browser?
Thanks
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
HttpURLConnection urlConnection = null;
try
{
//URL url = new URL("http://www.deanblakely.com/myRESTService/SayHello");
URL url = new URL("http://localhost:61420/api/products");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
String myString = readStream(in);
String otherString = myString;
otherString = otherString + " ";
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
urlConnection.disconnect();
}
}
private String readStream(InputStream is)
{
try
{
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int i = is.read();
while(i != -1)
{
bo.write(i);
i = is.read();
}
return bo.toString();
}
catch (IOException e)
{
return "" + e;
}
}
}
Visual Studio development web server will only accept connections from the local host and not over the network or other virtual connection. Sounds like AVD is seen as a remote host.
To access the app from anywhere, change the webserver that should be used. Assuming you're using Windows 7 and Visual Studio 2010, make sure you have IIS and all required features installed and set the local IIS as the webserver in your project settings:
It could be necessary to start Visual Studio as a Administrator to run it with local IIS.
Use the actual IP address of your machine ie, http://192.168.0.xx
Only your local machine can access localhost, and if you are on the emulator or a device, it will have a different IP through either NAT or your DHCP from the router.
Related
When I connect to MySQL in android:
code show as below
protected static void connMysql(){
Connection conn = null;
PreparedStatement pstm = null;
ResultSet res = null;
String openurl_mysql="jdbc:mysql://10.15.26.21:3306/etrack_user&autoReconnect=true&failOverReadOnly=false";
try {
java.sql.Driver.class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(openurl_mysql,"etrack","_etrack_mysql_");
pstm = conn.prepareStatement("select count(*) as count from et_patrol_task");
res = pstm.executeQuery();
while(res.next()){
int count = res.getInt("count");
System.out.println("return success=============="+count);
}
res.close();
pstm.close();
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
When I run the program,I get the following problem:enter image description here
Has anyone encountered a similar problem or solved it?
You can't access a MySQL DB from Android natively.Actually you may be able to use JDBC, but it is not recommended.
JDBC is infrequently used on Android, and I certainly would not recommend it.
IMHO, JDBC is designed for high-bandwidth, low-latency, highly-reliable network connections (e.g., desktop to database server, Web application server to database server). Mobile devices offer little of these, and none of them consistently.
I am trying to connect a simple android client to a simple java server on another computer running on the same wi-fi network, i was able to connect with a java code(non android) on eclipse, and the server works just fine, but when i take the same code and put in my android app (android studio), it throws an IOException.
As of right now my protocol just returns a string "yay" and i just want to display it in a View.
My code:
private void createCom2(TextView showResult){
Socket pazeSocket = null;
PrintWriter pw = null;
BufferedReader br = null;
String ip = "10.0.0.4";
try {
pazeSocket = new Socket(ip, 4444);
pw = new PrintWriter(pazeSocket.getOutputStream());
br = new BufferedReader(new InputStreamReader(pazeSocket.getInputStream()));
} catch (UnknownHostException e) {
Toast.makeText(this,"Don't know about host: " + ip , Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this,"Couldn't get I/O for the connection to: " + ip , Toast.LENGTH_SHORT).show();
}
}
Thanks.
You need Internet permission for your app. Add this line to your manifest file:
<uses-permission android:name="android.permission.INTERNET"/>
and read more abut permissions here, if you like:
http://developer.android.com/guide/topics/manifest/manifest-intro.html
Im trying to get a HTTPS Server running in my Android App. I've decided to do it with Jetty (Version 7.0.2). My Problem is that I can't get the Server working. The HTTP Connector works fine, but whenever I try to connect to the HTTPS Connector the Android Browser tells me:
Connection Problem: Couldn't establish a secure connection.
Heres the Code I'm using:
server = new Server(8080);
SelectChannelConnector connector0 = new SelectChannelConnector();
connector0.setPort(8080);
connector0.setMaxIdleTime(30000);
connector0.setRequestHeaderSize(8192);
SslSelectChannelConnector ssl_connector = new SslSelectChannelConnector();
ssl_connector.setPort(8443);
SslContextFactory cf = ssl_connector.getSslContextFactory();
cf.setKeyStore("keystore");
cf.setKeyStorePassword("password");
cf.setKeyManagerPassword("password");
server.setConnectors(new Connector[]{ connector0, connector1});
server.setHandler(new HelloHandler());
try {
server.start();
server.join();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
As mentioned before the SelectChannelConnector works fine, but the SslSelectChannelConnector doesn't. I'm using a BKS keystore created by portecle. Is there anything wrong in my Code? Or is there a problem with Android?
Thanks for your help
I am trying to send data from my Android phone to my home-server by using sockets. My server runs Linux so I used Perl to code the script for my server. The connection works fine and I can send data to my client running on the phone.
Problem is, when I send something (first try was a simple string) to the server, I don't receive anything at the servers side. Everything works fine if I use telnet to send a string to the server.
I am sitting here for some time now and I looked if there was a similar question to mine and could not find any in which the problem is discussed for Android to Perl-script. Here is my code for the Android app:
try {
Socket socket = new Socket("192.168.178.22", 22222);
Statusinformation("connection with server succeed");
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Statusinformation(input.readLine());
OutputStream outstream =socket.getOutputStream();
PrintWriter out = new PrintWriter(outstream);
out.println("This is a test message from client on phone!\n");
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
Statusinformation("connection unsucsessfull");
e.printStackTrace();
}
on my phone I receive this if i execute the above code:
connection with server succeed!
and on the server side I'm using this code to receive the string from socket clients:
use IO::Socket;
my $server = IO::Socket::INET -> new(
Proto => 'tcp',
LocalPort => 22222,
Listen => SOMAXCONN,
);
print "Server started..\n";
while (1) {
next unless my $conect = $server -> accept();
my $childconection = fork;
if ($childconection == 0) {
handle_connection($conect);
}
}
sub handle_connection
{
my $sock = shift;
my $client_message="";
my $client_addr = $sock -> peerhost;
print "connection: $client_addr connected\n";
print $sock "hi $client_addr, you are connected!\n";
while (1) {
open (Tempfile, '>>tempfile.txt');
while ($client_message = <$sock>) {
print Tempfile $client_message;
print $client_message;
}
close (Tempfile);
}
close($sock);
exit(0);
}
ok now I am a little ashamed.
I solved the problem by adding:
out.flush();
the flush() method assures that all pending data is send to the target and flushs the target.
This is the situation I'm facing with the code below:
As you can see I'm trying to read an HTTP stream. When I run the following code on the Android simulator it works 100% of the time, when I run the following code on my Galaxy S3 while on 3G it works 100% of the time, when I try to connect to the URL using my laptop browser it works 100% of the time, when I try to connect using the Galaxy S3 browser (in both wifi and 3g) it works... 100% of the time. HOWEVER, when I try to connect using my Galaxy S3 while on Wi-Fi I time out ~80% of the time. If I remove the timeout properties I get weird exceptions such as:
"recvfrom failed: ETIMEDOUT"
"failed to connect to <URL>: connect failed: ENETUNREACH (Network is unreachable)"
"unable to resolve the host <URL>: no address associated with hostname"
I'm open to any suggestions...
public static final String getHttpResponse(String url)
{
HttpURLConnection conn = null;
InputStream response = null;
try {
URL address = new URL(url);
conn = (HttpURLConnection)address.openConnection();
conn.setConnectTimeout(30 * 1000); //30 seconds
conn.setReadTimeout(30 * 1000); //30 seconds
response = conn.getInputStream();
if(conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.e("Util.getHttpResponse", Integer.toString(conn.getResponseCode()));
return null;
}
String result = Util.streamToString(response);
return result;
} catch(IOException e) {
response = conn.getErrorStream();
Log.e("Util.getHttpResponse", Util.streamToString(response));
return null;
} finally {
if( response != null ) {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn != null) {
conn.disconnect();
}
}
}
UPDATE:
- using AndroidHttpClient did not work
- After getting the input stream I had an error popup right in the eclipse IDE... As you can see my debug cursor made it all the way to line 107.. well after I was done getting the input stream this time...
I got the same problem on Android device. I use an IP address in the url. Final, I found the HttpURLConnection.connect(...) method involved the getHostName() internally. After that, I use the domain in the url, then it works 100% of the time.
As an experiment, what if you try using AndroidHttpClient class instead for doing the same? It has some predefined timeouts and other settings which, we were told, should work fine in most cases.