I'm having problems with an app that works when connecting to a remote web server, running a php script against a database. However, when I point the same app to my local web server running on my machine, things doesn't work.
Here's the code I use for connecting to the remote web server (it needs authentication):
(All the networking code is done inside an AsyncTask class.)
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
StringBuilder authentication = new
StringBuilder().append("frankh").append(":").append("vriceI29");
result = Base64.encodeBytes(authentication.toString().getBytes());
httppost.setHeader("Authorization", "Basic " + result);
nameValuePairs.add(new BasicNameValuePair("date", date));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
For the connection to the local server, which doesn't use authentication, I'm commenting out these lines:
//StringBuilder authentication = new
// StringBuilder().append("frankh").append(":").append("vriceI29");
//result = Base64.encodeBytes(authentication.toString().getBytes());
//httppost.setHeader("Authorization", "Basic " + result);
However, I get two different errors, depending on how I phrase the url to the local web server.
If I use this url: "http://localhost.shoppinglistapp/fetchlist.php"
I get this error:
Error in http connectionjava.net.UnknownHostException: localhost.shoppinglistapp
If I skip the http part in the url, I get this error:
Error in http connectionjava.lang.IllegalStateException: Target host must not be null,
or set in parameters.
What am I doing wrong here? The remote server is a Linux Apache server, and the local server is IIS 7. The local server is supposed to be just for working on when I've got no or a bad internet connection, so it's not critical, but I hate not knowing why things doesn't work.
If you testing via your local emulator, you'll want to use 10.0.2.2 instead of 'localhost'.
Referring to localhost from the emulated environment
Related
The command is
curl http://localhost:port -H 'Authorization: Token token=blahblahblah'
I am currently using this approach:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String authString = "Token " + "3589c4cd8c18f077bf43b4c4b7415d"; // <~token
httpPost.setHeader("Authorization", authString);
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
I just get a bad token back meaning that I did not successfully login from my android client. However the curl command i post works fine. So I believe I am not implementing the http Post correctly on my app. Thanks!
Your curl command has the header as:
Token token=blahblahblah
Your Java has the header as:
Token 3589c4cd8c18f077bf43b4c4b7415d
You are missing the token= part.
Also, HttpClient was deprecated in Android 5.1 and is removed from the Android SDK in Android 6.0. I encourage you to move to some other HTTP API. That could be:
the built-in classic Java HttpUrlConnection
Apache's independent packaging of HttpClient for Android
OkHttp (my recommendation)
AndroidAsync
Or, depending upon the nature of your HTTP work, you might choose a library that supports higher-order operations (e.g., Retrofit for Web service APIs).
I'm trying to fetch an image from the AppEngine server in development mode, using this code from here:
HttpGet httpRequest = new HttpGet(URI.create(url) );
HttpClient httpclient = new DefaultHttpClient();
HttpResponse resp = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = resp.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream instream = bufHttpEntity.getContent();
bmp = BitmapFactory.decodeStream(instream);
When executing the 3rd line (httpclient.execute(..)) I get the error:
W/System.err(508): org.apache.http.conn.HttpHostConnectException:
Connection to http://0.0.0.0:8888 refused
This URL http://0.0.0.0:8888 is correct I believe, because in this App Engine connected Android project, I'm able to fetch images with this address on the browser client side of the project. (Again, I'm in local development mode)
Why is this connection being refused? Thanks.
http://0.0.0.0:8888 is certainly not correct. You need to use the IP address of the computer where the App engine development server is running. If you are on a local network that would be something like 192.168.x.xxx. Type ipconfig on Windows or /sbin/ifconfig on Linux in a a terminal to find out the address of your development machine. Then use that to access it from Android.
I am trying to connection with php-MySQL using below code
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://127.0.0.1/mytable.php");
// HttpPost httppost = new HttpPost("http://localhost/mytable.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
when control goes on httpclient.execute(httppost); it throws an exception:
org.apache.http.conn.HttpHostConnectException: Connection to http://127.0.0.1 refused
I also add <uses-permission android:name="android.permission.INTERNET" /> to my AndroidManifest.xml file.
When I test my php file directly from a browser, it works fine. Any suggestions?
From the emulator, il you want to access your physical computer, you must use the following IP address :
10.0.2.2
The one you used, 127.0.0.1, points to the machine inside which your code is executed -- i.e. the emulator itself.
As you don't have an HTTP server running on your Android emulator, your application cannot connect to it -- which explains the error message you get.
For more informations, you should read the following section of the manual : Network Address Space
127.0.0.1 is localhost, the current device. On your computer, it refers to your computer, but on a device or an emulator it refers to that device.
See this document on how to refer to the localhost of your computer when running within an emulator. Alternatively, you can change 127.0.0.1 to your computer's actual IP address.
http://developer.android.com/resources/faq/commontasks.html#localhostalias
I'm trying to authenticate an android client app to my server ruby on rails app which uses Devise gem. But I've tried http authentication, and post requests to authenticate, and the server just responds 200 for any given username/password.
I've already set up the config.http_authenticatable = true and the :database_authenticable at the user model...
I'll post my authenticate method so u guys can have a look on it...
public static boolean authenticate(User user, String verb) throws IOException, JSONException
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(verb);
CredentialsProvider credProvider = new BasicCredentialsProvider();
credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
new UsernamePasswordCredentials(user.getMail(), user.getPassword()));
httpClient.setCredentialsProvider(credProvider);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email", user.getMail()));
nameValuePairs.add(new BasicNameValuePair("password", user.getPassword()));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
int statusCode = httpResponse.getStatusLine().getStatusCode();
//JSONObject resp = null;
if (statusCode < 200 || statusCode >= 300){
throw new IOException("Error");
}
return true;
}
If server is responding 200, it really sounds like server side configuration, so you should double-check your URLs are actually secured, using a desktop web browser and a tool like Fiddler so you can see everything. Pay particular attention to the Authentication headers, and the Status codes; at the least you should see a 401 from the server to start things off.
You can also turn on diagnostics for Apache HTTP on your device, and it will also dump headers and content to LOGCAT, so you can make sure everything is proceeding.
Check the WWW-Autnenticate header's contents, it will specify which schemes are accepted. The client side will re-request the URL, but it will put the Authorization header into its request.
In short, make sure your server side works outside of your application, in an environment that's easier to troubleshoot.
Client side, it looks like you are only activating BASIC authentication (everyone stop using it!), and your endpoint may only want DIGEST or NTLM or KERBEROS or any other authentication scheme than BASIC. Since it looks like you didn't set up for SSL, certainly use at least DIGEST or you have clear text issues!
Using form variables (for authentication) only works at the application level, and not the HTTP protocol level, which uses HTTP Headers (WWW-Autnenticate, Authorization) and Status codes (401, 403) for the authentication process. And again, if you aren't configuring your server (and client) for SSL-only, there will be clear text problems.
I'm trying to debug a little problem I have with a web service. I cannot POST to the webservice, but I can GET just fine.
When I try to post data to the webservice I get a HTTP 1/1 400 Bad Request.
Is there a way I can see more details?.. I dont have access to the server, on which the webservice is hosted
HTTP Post code
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://lino.herter.dk/Service.svc/Data/");
StringBuilder sb = new StringBuilder();
StringEntity se = new StringEntity("test");
se.setContentType("text/xml");
httppost.setHeader("Content-Type","text/xml");
httppost.setEntity(se);
HttpResponse response2 = httpclient.execute(httppost);
sb = inputStreamToString(response2.getEntity().getContent());
It might be easiest to set up Wireshark on your development machine, and capture the traffic between your Android and the server. You'll have to run Wireshark in Promiscuous mode, which I think is the default option.