开发者

Https request, authentication in Android

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.

imp开发者_如何学Goort 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!!!


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" />


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜