2012-02-20 188 views
2

我有以下代碼需要正常的HTTP GET請求並將輸出html作爲字符串返回。在Android中獲取HTTPS GET請求的內容

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

我想實現同樣的事情無符號SSL證書,但我有點在Java或者Android的編程新手,並找到類似的問題非常混亂以前的一些反應。

有人可以更改上面的代碼以使用HTTPS請求嗎?

另一個問題是,如果我通過GET請求發送未加密的數據並將數據庫條目打印到函數返回內容的網頁上,是否會存在中間人攻擊的風險。使用POST請求會更好嗎?

我選擇使用SSL的原因是因爲有人告訴我發送的數據是加密的。數據是敏感的,如果我發送像localhost/login.php?user = jim & password = sd7vbsksd8這將返回「user = jim權限=管理員年齡= 23」這是我不希望別人看到的數據他們只是使用瀏覽器併發送相同的請求。

回答

1

試試這個:

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

我們可以參數添加到HTTP GET請求作爲

HttpGet method = new HttpGet("http://w3mentor.com/download.aspx?key=valueGoesHere"); 
client.execute(method); 

的Android應該使用SSL自動工作。也許在本地主機上使用的SSL證書不可信?選中此項:Trusting all certificates using HttpClient over HTTPS

檢查您是否可以使用瀏覽器瀏覽https://yourhost/login.php?user=jim&password=sd7vbsksd8

+0

謝謝,當我使用您提供的鏈接時,這樣做的伎倆。 – 2012-02-21 17:25:03