2010-06-22 234 views
5

我目前正在尝试通过http获取调用与服务器进行身份验证。下面提供的代码在java项目中编译时工作。将正确的标记返回到程序。然而,无论何时我尝试在Android中实现相同的代码,我都不会收到通过Get调用返回的令牌。HTTPS请求,Android中的身份验证

在Android中,我在函数中返回inputLine,但inputLine始终是一个空字符串。 system.out.println()打印返回的标记。

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(); 
    } 
} 
} 

感谢您的帮助!

+0

?访问日志,状态代码等 – 2010-06-22 15:55:10

+0

不幸的是,服务器托管在外 – Mango 2010-06-23 07:24:18

+0

当我在Android中运行代码时,它似乎总是在“InputStream ins - con.getInputStream();”行中失败。它抛出IOException。但是,当我将代码作为Java应用程序运行时,不会发生这种情况。 – Mango 2010-06-23 08:12:32

回答

2

您可能没有将Internet-Permission添加到您的项目AndroidManifest.xml中。 如果是这样,添加下面的线为<manifest/>节点的子:

<uses-permission android:name="android.permission.INTERNET" /> 
2

我使用POST和FormEntity从服务器获取数据(如认证),我也从来没有任何问题:

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()); 
[...] 

也许你可以看到发生了什么,在服务器端,你会发现这个有用

+0

这看起来对于SSL来说非常简单,我很惊讶没有使用SchemeRegistry来注册这个人的“https”方案:http://stackoverflow.com/questions/2603691/android-httpclient-and-https/2603786#2603786 – 2011-06-07 20:39:19