2010-06-22 237 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