I am working on an Android web server.When i go to localhost:8080 on the emulator browser, it serves a page/form with a password field. On successful verification of the password, I would like to redirect the user to the success/failure page.What would be the best way to read the incoming http post request and parse the password field for verification?Any pointers in the right direction would be greatly appreciated. I have a handler for the url to which the form is submitted. The code for the handler is:
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.entity.ContentProducer;
import org.apache.http.entity.EntityTemplate;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import android.content.Context;
public class LoginHandler implements HttpRequestHandler {
private Context context = null;
public LoginHandler(Context context) {
this.context = context;
}
#Override
public void handle(final HttpRequest request, HttpResponse response,
HttpContext httpcontext) throws HttpException, IOException {
HttpEntity entity = new EntityTemplate(new ContentProducer() {
public void writeTo(final OutputStream outstream) throws IOException {
String resp = null;
OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
if(validatePassword()==true){
resp ="<html><head></head><body><h1>Home<h1><p>Success.</p></body></html>";
}
else{resp="<html><head></head><body><h1>Home<h1><p>Login Failed.</p></body></html>";}
writer.write(resp);
writer.flush();
}
});
response.setHeader("Content-Type", "text/html");
response.setEntity(entity);
}
boolean validatePassword(){
boolean pass=false;
//parse request body here and check for the password if true return true/else false
return pass;
}
}
After looking around for ages I found the solution. Adding the following in the handle method does the trick.Thanks to the original poster
.http://www.androiddevblog.net/android/a-bare-minimum-web-server-for-android-platform
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
if (entity != null) {
Log.v("RequestBody", EntityUtils.toString(entity, "UTF-8"));
entity.consumeContent();
}
}
I apologize if this isn't quite what you're asking, so if it's not, let me know.
You could use a JSONObject to return whether or not that password was verified as correct.
For example, if the password is correct, you could store the HTTP result as:
{"status":200,"confirmed":"true"}
Or "false" otherwise.
When you get back from the HTTP Post Request, you can store this result as a String, then make a JSONObject out of it. For example:
// Send the URL to a postRequest function and return the result as a String
String output = makePostRequest(url);
// Parse the String as a JSONObject and receive whether or not the login was confirmed
JSONObject o = new JSONObject(output);
String confirmed = o.getString("confirmed");
if (confirmed.equals("true")) {
// Password confirmed - redirect user to success page
} else {
// Password incorrect - redirect user to failure page
}
Note: in case you need an idea of how to receive the response code from the post request, here's some sample code:
String output = {};
// Use bufferedreader and stringbuilder to build an output string (where conn is your HTTPUrlConnection object you used to make the post request
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
// Loop through response to build JSON String
while((line = br.readLine()) != null) {
sb.append(line + "\n");
}
// Set output from response
output = sb.toString();
And now output is the String you can turn into a JSONObject.
Does any of this help?
Edit:
Okay, so the String you will be getting will be in the format of {"password":"somepassword"}. To parse this, try this out:
String s = /* the string in the format {"password":"somepassword"} */
JSONObject o = new JSONObject(s);
String password = o.getString("password");
if (password.equals(random_password_at_beginning_of_webservice) {
// Password confirmed - redirect user to success page
} else {
// Password incorrect - redirect user to failure page
}
Related
Is there any way to implement NTLM Authentication with HttpURLConnection? Currently I have implemented it with DefaultHttpClient and JCIFSEngine for the authentication scheme. ( My inspiration was : Android: NTLM Authentication, ksoap, and persistent connections)
But since Android 6 Apache HTTP Client Removal, I was looking for a solution besides adding useLibrary 'org.apache.http.legacy' in app gradle file, cause I want to improve my code using HttpURLConnection class instead. As documentation says, this API is more efficient because it reduces network usage through transparent compression and response caching, and minimizes power consumption.
HttpURLConnection can work with NTLM only if you add library jcifs.
This example works with latest jcifs-1.3.18 :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.impl.auth.NTLMEngineException;
public class TestNTLMConnection {
public static void main(String[] args) throws UnknownHostException, IOException, NTLMEngineException {
// Method 1 : authentication in URL
jcifs.Config.registerSmbURLHandler();
URL urlRequest = new URL("http://domain%5Cuser:pass#127.0.0.1/");
// or Method 2 : authentication via System.setProperty()
// System.setProperty("http.auth.ntlm.domain", "domain");
// System.setProperty("jcifs.smb.client.domain", "domain");
// System.setProperty("jcifs.smb.client.username", "user");
// System.setProperty("jcifs.smb.client.password", "pass");
// Not verified // System.setProperty("jcifs.netbios.hostname", "host");
// System.setProperty("java.protocol.handler.pkgs", "jcifs");
// URL urlRequest = new URL("http://127.0.0.1:8180/simulate_get.php");
HttpURLConnection conn = (HttpURLConnection) urlRequest.openConnection();
StringBuilder response = new StringBuilder();
try {
InputStream stream = conn.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(stream));
String str = "";
while ((str = in.readLine()) != null) {
response.append(str);
}
in.close();
System.out.println(response);
} catch(IOException err) {
System.out.println(err);
} finally {
Map<String, String> msgResponse = new HashMap<String, String>();
for (int i = 0;; i++) {
String headerName = conn.getHeaderFieldKey(i);
String headerValue = conn.getHeaderField(i);
if (headerName == null && headerValue == null) {
break;
}
msgResponse.put(headerName == null ? "Method" : headerName, headerValue);
}
System.out.println(msgResponse);
}
}
}
Warning: jcifs ignores the connectTimeout and readTimeout you define with the library, it's the reason why the connection takes ages to break when the host is not responding. Use the code I describe in this SO thread to avoid this bug.
I'm making an app which let people login, sign in, sign up, write something and save it to database.
So I decided to chose Restful Api with Slim Framework. I publish it in my host and test by extension of google chrome call Advanced Rest Client. Everything like login ,signin, sign up, wite something, update it, delete it.. work fine.
For example:
I log in with information:
email: stark#gmail.com
password: abc
then the result is something like that.
{
error: false
name: "Kien"
email: "nguyenkien1402#yahoo.com"
apiKey: "fc2aee103c861026cb53fd8920b10adc"
createdAt: "2015-06-24 00:28:01"
}
But when I used it in my android app. I cannot connect and get information by JSON.
Please tell my how to solve this problem.
Thank you.
Sorry about my english, it's not native english.
To connect to the restful API, the following steps you have to do
give internet access
have to do http connection
have to to take stream input
Give Internet Access
to give internet access to the app we have to add this piece of code in the file " AndroidManifest.xml"
<uses-permission android:name="android.permission.INTERNET"/>
To do the second and third step we have to create a new java class as when we are connecting to the restful API, it will run in the background and MainActivity does not allow the background task.
Let say we create a new java class "fetchData" to get data from the API.
to do the remaining task we have to use this piece of code
URL url = new URL(API ADDRESS);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
now you get the JSON file using the "Bufferedreader.readLine()"
then the class file looks like this
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class fetchData extends AsyncTask<Void,Void,Void> {
String data ="";
String dataParsed = "";
String singleParsed ="";
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("https://api.myjson.com/bins/k3p10");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
JSONArray JA = new JSONArray(data);
for(int i =0 ;i <JA.length(); i++){
JSONObject JO = (JSONObject) JA.get(i);
singleParsed = "Name:" + JO.get("name") + "\n"+
"email:" + JO.get("email") + "\n"+
"Error:" + JO.get("error") + "\n";
dataParsed = dataParsed + singleParsed +"\n" ;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
from the JSON array, you can extract everything from the JSON you get from the API. then you can use the information as per your requirement.
If your url is generating json response, then you have to read that.
public static String sendGet(String url) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString(); //here is your response which is in string type, but remember that the format is json.
}
Then convert your response to json:
JsonObject obj = new JsonObject(response);
I solved it.
It up to my class about CRUD JSON.
Thank you.
I've recently been working on an Android app using Android Studio which is using a Django backend. The web application is already in place I just want to make the app in Android for it.
The problem I am running in to, which is mostly because I'm new to app development, is the login authentication. I've researched on this topic here and I understand theoretically how I should go about doing this, but I have not been successful in logging in from my app.
The problem I have is this:
I get a csrf token authentication failure. It states that the cookie is not set. I understand that a post request will return this.
I am always getting a success transition in my doPost method.
I currently am lost in how to check if I have actually logged in or not. And the only solution I thought of for the cookie not being set is to do a Get request, parse the cookie as a string and pass that in to the post request. But I'm not sold on it being the best strategy. The bigger problem is not being able to tell if I have actually logged in or not. How can I check that? I have read posts on kind of explaining how to do this but as a beginner it is hard to translate that to code. How do I check if the user was actually authenticated? Any and all help is appreciated.
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mEmail;
private final String mPassword;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
#Override
protected Boolean doInBackground(Void... params) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", mEmail));
postParameters.add(new BasicNameValuePair("password", mPassword));
String response = null;
String get_response = null;
try
{
response = SimpleHttpClient.executeHttpPost(localLoginUrl, postParameters);
Log.d("Login Activity","Post Response is: " + response);
}
catch (Exception e)
{
Log.d("Login Activity","Error is: " + e.toString());
e.printStackTrace();
return false;
}
return true;
}
public static String executeHttpPost(String url,
ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The Django view:
def login_view(request): # Login page view
form = login_form()
if request.method == 'POST':
form = login_form(request.POST)
if form.is_valid(): # check if form is valid
user = authenticate(
username=form.cleaned_data['username'],
password=form.cleaned_data['password']) # authenthicate the username and password
login(request, user) # login the user
# Once logged in redirect to home page
response = HttpResponseRedirect("/"+some_user_url+"/home")
print "USER KEY IS: %s" % some_user_key
response.set_cookie('some_user_key', value=some_user_value, max_age=some_max_age, secure=SESSION_COOKIE_SECURE, httponly=False)
return response
else:
form = login_form() # Display empty form
return render(request, "login.html", { # loads the template and sends values for the template tags
'form': form,
})
I know the questions was asked quite a long time ago but, since there's no answer, and I'm working quite intensively with Django recently, I thought to share my very basic knowledge, hoping it will be of help for others.
The way you are dealing with the CSRF token is the correct one: first you perform a get of the login page which will give you the CSRF token in the cookie. You store the cookie and the CSRF token and you embed them in the following POST request, together with authentication data. If you get a 200 OK from the server it already means you correctly used the CSRF token, and this is an awesome start :)
In order to troubleshoot whether the user has actually logged in or not, that is whether it's credentials were accepted, you can print out the payload of the HTTP response you obtained from the server.
I use a function which prints me the response of the server in case I get an error code greater than 400. The code is the following:
public static boolean printHTTPErrorMsg(HttpURLConnection c) {
boolean error = false;
StringBuilder builder = new StringBuilder();
try {
builder.append(c.getResponseCode());
builder.append("\n");
builder.append(c.getResponseMessage());
System.out.println("RESPONSE CODE FROM SERVER");
System.out.println(builder);
InputStream _is;
if(c.getResponseCode()>=400){
error = true;
_is = c.getErrorStream();
final BufferedReader reader = new BufferedReader(
new InputStreamReader(_is));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return error;
}
You need to tweak it because when you get a 200 OK from the server, there's no ErrorStream but simply an InputStream. So if you change your if condition to =200 and replace the getErrorStream() with getInputStream() you'll see in the log what is actually the content of the response of the server. Typically, if the login failed, the response will contain most likely the HTML code of the login page with the error message saying you provided wrong credentials.
Hope this helps
I am trying to input text from Android into websites, and I read that httppost is a good option. I download the HttpClient 4.2.2 (GA) tar.gz, unzipped them, and copied the 7 jars into the lib folder of my android project in Eclipse. I'm pretty sure I got all the jars, since they matched those listed on the website.
I then proceeded to copy and paste the top tutorial from: http://hc.apache.org/httpcomponents-client-ga/quickstart.html
I imported everything, and was left with this error:
EntityUtils.consume(entity1); //X
} finally {
httpGet.releaseConnection(); //X
This portion of code is at two places in the tutorial, and errors occur at both.
Eclipse says for the first line:
"The method consume(HttpEntity) is undefined for the type EntityUtils."
Second line:
"The method releaseConnection() is undefined for the type HttpGet."
I'm pretty sure I downloaded every jar, transported them correctly, and imported everything. What is making the error? Thanks.
Here is what I have now. Edward, I used some of the code from your methods, but just put them into onCreate. However, this isn't working. A few seconds after I go from the previous activity to this one, I get the message that the app "has stopped unexpectedly".
I have a question about inputting my Strings into the website text fields: Do I use NameValuePairs of HttpParams? Here's my code, can you see what's wrong? Thanks.
package com.example.myapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
public class BalanceCheckerActivity extends Activity {
private final String LOGIN_URL = "https://someloginsite.com"; //username and password
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_balance_checker);
String username = getIntent().getExtras().getString("username");
String password = getIntent().getExtras().getString("password");
//Building post parameters, key and value pair
List<NameValuePair> accountInfo = new ArrayList<NameValuePair>(2);
accountInfo.add(new BasicNameValuePair("inputEnterpriseId", username));
accountInfo.add(new BasicNameValuePair("password", password));
//Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
//Creating HTTP Post
HttpPost httpPost = new HttpPost(LOGIN_URL);
BasicHttpParams params = new BasicHttpParams();
params.setParameter("inputEnterpriseID", username);
params.setParameter("password", password);
httpPost.setParams(params);
//Url Encoding the POST parameters
try {
httpPost.setEntity(new UrlEncodedFormEntity(accountInfo));
}
catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
startActivity(new Intent(this, AccountInputActivity.class));
}
HttpResponse response = null;
InputStreamReader iSR = null;
String source = null;
// Making HTTP Request
try {
response = httpClient.execute(httpPost);
// writing response to log
Log.d("Http Response:", response.toString());
iSR = new InputStreamReader(response.getEntity().getContent());
BufferedReader br = new BufferedReader(iSR);
source = "";
while((source = br.readLine()) != null)
{
source += br.readLine();
}
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
startActivity(new Intent(this, AccountInputActivity.class));
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
startActivity(new Intent(this, AccountInputActivity.class));
}
System.out.println(source);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_balance_checker, menu);
return true;
}
}
That mostly looks pretty good to me. I only saw one obviously wrong piece of code in it:
while((source = br.readLine()) != null)
{
source += br.readLine();
}
That's kind of a mess, and rather than try to untangle it, I'll just rewrite it.
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null)
sb.append(line);
String source = sb.toString();
Also, you shouldn't be doing network I/O from onCreate() or even from within your UI thread, since it can block for a long time, freezing your entire UI and possibly causing an "Application Not Responding" (ANR) crash. But for a simple test program, you can let that slide for now. For production code, you'd launch a thread or use AsyncTask().
Anyway, we're not really interested in building and debugging your program for you. Have you tried this code out? What was the result?
One final note: a login sequence like this is likely to return an authentication token in the form of a cookie. I forget how you extract cookies from an HttpResponse, but you'll want to do that, and then include any received cookies as part of any subsequent requests to that web site.
Original answer:
I think you've gotten yourself all tangled up. The Apache http client package is built into Android, so there's no need to download any jar files from apache.
I'm not familiar with EntityUtils, but whatever it is, if you can avoid using it, I would do so. Try to stick with the bundled API whenever possible; every third-party or utility library you add to your application increases bloat, and on mobile devices, you want to keep your application as light as possible. As for the actual "consume()" method not being found, that's probably a mistake in the documentation. They probably meant consumeContent().
The releaseConnection() call is probably only necessary for persistent connection. That's relatively advanced usage; I don't even do persistent or managed connections in my own code.
You haven't provided enough information to let us know what it is you're trying to do, but I'll try give you a reasonably generic answer.
There are many, many ways to transmit data to a server over the http protocol, but in the vast majority of cases you want to transmit form-encoded data via HttpPost.
The procedure is:
Create a DefaultHttpClient
Create an HttpPost request
Add headers as needed with setHeader() or addHeader().
Add the data to be transmitted in the form of an HttpEntity
Call client.execute() with the post request
Wait for and receive an HttpResponse; examine it for status code.
If you're expecting data back from the server, use response.getEntity()
There are many HttpEntity classes, which collect their data and transmit it to the server each in their own way. Assuming you're transmitting form-encoded data, then UrlEncodedFormEntity is the one you want. This entity takes a list of NameValuePair objects which it formats properly for form-encoded data and transmits it.
Here is some code I've written to do this; these are only code fragments so I'll leave it to you to incorporate them into your application and debug them yourself.
/**
* POST the given url, providing the given list of NameValuePairs
* #param url destination url
* #param data data, as a list of name/value pairs
*/
public HttpResponse post(String url, List<NameValuePair> data) {
HttpPost req = new HttpPost(url);
UrlEncodedFormEntity e;
try {
e = new UrlEncodedFormEntity(data, "UTF-8");
} catch (UnsupportedEncodingException e1) {
Log.e(TAG, "Unknown exception: " + e1);
return null; // Or throw an exception, it's up to you
}
return post(req, e);
}
/**
* Post an arbitrary entity.
* #param req HttpPost
* #param data Any HttpEntity subclass
* #return HttpResponse from server
*/
public HttpResponse post(HttpPost req, HttpEntity data) {
try {
HttpClient client = new DefaultHttpClient();
req.setEntity(data);
HttpResponse resp = client.execute(req);
int status = resp.getStatusLine().getStatusCode();
if (status != HttpStatus.SC_OK) {
Log.w(TAG,
"http error: " + resp.getStatusLine().getReasonPhrase());
return null; // Or throw an exception, it's up to you
}
return resp;
} catch (ClientProtocolException e) {
Log.e(TAG, "Protocol exception: " + e);
return null;
} catch (UnknownHostException e) {
return null;
} catch (IOException e) {
Log.e(TAG, "IO exception: " + e);
return null;
} catch (Exception e) {
// Catch-all
Log.e(TAG, "Unknown exception: " + e);
return null;
}
}
I have the following code which takes a normal HTTP GET Request and returns the output html as a string.
public static String getURLContent(String URL){
String Result = "";
String IP = "http://localhost/";
try {
// Create a URL for the desired page
URL url = new URL(IP.concat(URL));
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
Result = Result+str+"~";
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return Result;
}
I would like to implement the same sort of thing for an unsigned ssl certificate but I am a bit of a novice at Java or Android programming and find some previous responses to similar questions very confusing.
Could someone change the code above to work with HTTPS requests?
One other question, would there be a risk of a middle-man-attack if I sent unencrypyted data via the GET request and print out database entries onto the webpage that the function returns the content of. Would it be better to use a POST request?
The reason I chose to use SSL is because someone told me that the data sent is encrypted. The data is sensitive and if I send something like localhost/login.php?user=jim&password=sd7vbsksd8 which would return "user=jim permission=admin age=23" which is data that I don't want others to see if they simply used a browser and sent the same request.
Try this:
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class TestHttpGet {
public void executeHttpGet() throws Exception {
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://w3mentor.com/"));
HttpResponse response = client.execute(request);
in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String page = sb.toString();
System.out.println(page);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
We can add parameters to an HTTP Get request as
HttpGet method = new HttpGet("http://w3mentor.com/download.aspx?key=valueGoesHere");
client.execute(method);
Android should automatically work with ssl. Maybe ssl certificate you are using on localhost is not trusted? Check this: Trusting all certificates using HttpClient over HTTPS
Check if you are able to browse https://yourhost/login.php?user=jim&password=sd7vbsksd8 using your browser.