2012-07-07 96 views
0

我正在嘗試登錄到網站,並顯示它的源代碼使用android模擬器,但我不能讓它的工作,但在基於Java的,它的工作。登錄並獲取源代碼

這裏是我的代碼:

package auth.test; 

import android.app.Activity; 
import android.os.Bundle; 
// used for interacting with user interface 
import android.widget.TextView; 
import android.widget.EditText; 
// used for passing data 
// used for connectivity 
import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.InputStreamReader; 
import java.io.OutputStreamWriter; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.net.URLConnection; 

public class AuthActivity extends Activity { 
/** Called when the activity is first created. */ 

//Handler h; 
private static URL URLObj; 
private static URLConnection connect; 
EditText eText; 
TextView tView; 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    tView=(TextView)findViewById(R.id.textView1); 
    initControls(); 
} 

    public void initControls() 
    { 

     try { 

      URLObj = new URL("http://students.usls.edu.ph"); 
      connect = URLObj.openConnection(); 
      connect.setDoOutput(true); 
     } 
     catch (MalformedURLException ex) { 
      tView.setText("The URL specified was unable to be parsed or uses an invalid protocol. Please try again."); 
      //System.exit(1); 
     } 
     catch (Exception ex) { 
      tView.setText("An exception occurred. " + ex.getMessage()); 
      //System.exit(1); 
     } 


     try { 

      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connect.getOutputStream())); 
      writer.write("username=0920204&password=******"); 
      //writer.close(); 


      BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream())); 

      String lineRead=""; 


      while((lineRead=reader.readLine())!=null) 
      { 
       tView.append(lineRead + "\n"); 
      } 


      reader.close(); 

     } 
     catch (Exception ex) { 
      tView.setText("There was an error reading or writing to the URL: " + ex.getMessage()); 
     } 
    } 
} 

所以,而不是顯示主網頁的源代碼,它顯示登錄頁面的源代碼。所以我認爲代碼的Bufferedwriter部分有問題。

回答

1

首先,您應該隱藏用戶名/密碼或僞造它們。

URLConnection處理餅乾非常糟糕。這就是爲什麼你只是從登錄頁面獲得結果。 Android自API 1開始內置Apache HttpClient,因此您可以使用它。餅乾管理得很好:-)

而且,你正在從服務器得到原始文本,而不是源代碼。