5

I am currently trying to authenticate with a server via a http Get call. The code provided below works when compiled in a java project. Returning the correct token to the program. However whenever I try to implement the same code in Android I do not get a token returned via the Get call.

In Android I am returning inputLine in a function, however inputLine is always an empty string.

The system.out.println() prints the returned token.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;

public class JavaHttpsExample 
{

public static void main(String[] args)
{   String inputLine = new String();
    try
    {
    String httpsURL = "https://the url";
    URL myurl = new URL(httpsURL);
    HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
    InputStream ins = con.getInputStream();
    InputStreamReader isr=new InputStreamReader(ins);
    BufferedReader in =new BufferedReader(isr);

    inputLine = in.readLine();

    System.out.println(inputLine);

    in.close();


    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
 }
}

thanks for your help!!!

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Mango
  • 281
  • 1
  • 3
  • 4

2 Answers2

2

You probably did not add the Internet-Permission to your projects AndroidManifest.xml. If so, add the following line as a child of the <manifest/> node:

<uses-permission android:name="android.permission.INTERNET" />
Tom
  • 5,068
  • 5
  • 29
  • 41
2

I'm using POST and FormEntity for retrieving data from the server (such as authentication), and i have never had any problems:

final String httpsURL = "https://the url";
final DefaultHttpClient client = new DefaultHttpClient();
final HttpPost httppost = new HttpPost(httpsURL);

//authentication block:
final List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
nvps.add(new BasicNameValuePair("userName", userName));
nvps.add(new BasicNameValuePair("password", password));
final UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
httppost.setEntity(p_entity);

//sending the request and retrieving the response:
HttpResponse response = client.execute(httppost);
HttpEntity responseEntity = response.getEntity();

//handling the response: responseEntity.getContent() is your InputStream
final InputSource inputSource = new InputSource(responseEntity.getContent());
[...]

maybe you'll find this usefull

rekaszeru
  • 19,130
  • 7
  • 59
  • 73
  • this seems really straight-forward for SSL, I'm surprised there's no use of SchemeRegistry to register the "https" scheme like this person did: http://stackoverflow.com/questions/2603691/android-httpclient-and-https/2603786#2603786 – Someone Somewhere Jun 07 '11 at 20:39