2014-03-28 100 views
1

好吧,夥計們,所以我最近開發的android應用程序將用戶的ID和密碼保存到SharedPreferences中。現在,當用戶第二次啓動應用程序時,他將通過listView中的幾個選項直接重定向到MainActivity。現在我頭痛不已,這讓我真的很瘋狂。我無法登錄網站並將數據提取到我的手機。我試過使用Http(s)UrlConnection,HttpClient,但它似乎並不適合我。我從POST方法獲得的所有信息都是登錄頁面的源代碼。Android:如何以編程方式登錄網站並從中檢索數據?

現在,有登錄頁面:https://medeine.vgtu.lt/studentams/login.jsp?klb=en

和我的目標頁:https://medeine.vgtu.lt/studentams/pask_stud.jsp < - 我需要從中獲取數據

你有什麼想法或建議/方法/指南/任何事情如何要做到這一點?

+0

什麼方法你所使用的登錄。你是否在webview中加載表單以獲取用戶憑證? –

+0

好吧,表格說:

因此我使用POST方法。不,我沒有使用webView。這個想法是獲取數據並以某種方式顯示在我自己的佈局中。 – env

+0

您是否認爲使用OAuth協議?登錄後,您可以與服務器交換數據。 –

回答

3

爲此,您必須發送兩個POST請求。在第一個請求中,如果成功登錄,則需要發送登錄數據並保存cookie。在第二個請求中,需要發送已保存的cookies並且您可以獲取數據。 數據爲POST格式必須是這樣的:var =值& VAR2 =數值

你的情況:

String data = "studKnNr=login&asmKodas=password"; 

和URL的請求:https://medeine.vgtu.lt/studentams/submit.jsp

看看下面的代碼:

String data = "studKnNr=login&asmKodas=password"; 
String loginUrl = "https://medeine.vgtu.lt/studentams/submit.jsp"; 
String Login = POST_req(loginUrl, data, 10000); /*last parameter is a limit of page content length*/ 

//And after succcess login you can send second request: 
String pageContent = POST_req(someUrl, "", 10000); 


//Methods for sending requests and saving cookie: 
//(this no needs for changing, can only past to you project) 
public String POST_req(String url, String post_data, int len) { 
    URL addr = null; 
    try { 
      addr = new URL(url); 
     } catch (MalformedURLException e) { 
      return "Некорректный URL"; 
     } 
     StringBuffer data = new StringBuffer(); 
     HttpURLConnection conn = null; 
     try { 
      conn = (HttpURLConnection) addr.openConnection(); 
     } catch (IOException e) { 
      return "Open connection error"; 
     } 
     conn.setRequestProperty("Connection", "keep-alive"); 
     conn.setRequestProperty("Accept-Language", "ru,en-GB;q=0.8,en;q=0.6"); 
     conn.setRequestProperty("Accept-Charset", "utf-8"); 
     conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); 
     conn.setRequestProperty("Cookie", ""); 
     conn.setDoOutput(true); 
     conn.setDoInput(true); 
     //conn.setInstanceFollowRedirects(true); 
     set_cookie(conn); 

     //POST data: 
     String post_str = post_data; 
     data.append(post_str); 
     try { 
      conn.connect(); 
     } catch (IOException e) { 
      return "Connecting error"; 
     } 
     DataOutputStream dataOS = null; 
     try { 
      dataOS = new DataOutputStream(conn.getOutputStream()); 
     } catch (IOException e2) { 
      return "Out stream error"; 
     } 
     try { 
      ((DataOutputStream) dataOS).writeBytes(data.toString()); 
     } catch (IOException e) { 
      return "Out stream error 1"; 
     } 

     /*If redirect: */ 
     int status; 
     try { 
      status = conn.getResponseCode(); 
     } catch (IOException e2) { 
      return "Response error"; 
     } 
     if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) { 
      String new_url = conn.getHeaderField("Location"); 
      String cookies = conn.getHeaderField("Set-Cookie"); 
      URL red_url; 
      try { 
       red_url = new URL(new_url); 
      } catch (MalformedURLException e) { 
       return "Redirect error"; 
      } 
      try { 
       conn = (HttpURLConnection) red_url.openConnection(); 
      } catch (IOException e) { 
       return "Redirect connection error"; 
      } 
      //conn.setRequestProperty("Content-type", "text/html"); 
      conn.setRequestProperty("Connection", "keep-alive"); 
      conn.setRequestProperty("Accept-Language", "ru,en-GB;q=0.8,en;q=0.6"); 
      conn.setRequestProperty("Accept-Charset", "utf-8"); 
      conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); 
      conn.setRequestProperty("Cookie", cookies);  
      conn.setDoOutput(true); 
      conn.setDoInput(true); 
      //conn.setInstanceFollowRedirects(true); 
     } 

     java.io.InputStream in = null; 
     try { 
      in = (java.io.InputStream) conn.getInputStream(); 
     } catch (IOException e) { 
      return "In stream error"; 
     } 
     InputStreamReader reader = null; 
     try { 
      reader = new InputStreamReader(in, "UTF-8"); 
     } catch (UnsupportedEncodingException e) { 
      return "In stream error"; 
     } 
     char[] buf = new char[len]; 
     try { 
      reader.read(buf); 
     } catch (IOException e) { 
      return "In stream error"; 
     } 
     get_cookie(conn); 

     return (new String(buf)); 
    } 
    public void get_cookie(HttpURLConnection conn) { 
     SharedPreferences sh_pref_cookie = getSharedPreferences("cookies", Context.MODE_PRIVATE); 
     String cook_new; 
     String COOKIES_HEADER; 
     if (conn.getHeaderField("Set-Cookie") != null) { 
      COOKIES_HEADER = "Set-Cookie"; 
     } 
     else { 
      COOKIES_HEADER = "Cookie"; 
     } 
     cook_new = conn.getHeaderField(COOKIES_HEADER); 
     if (cook_new.indexOf("sid", 0) >= 0) { 
      SharedPreferences.Editor editor = sh_pref_cookie.edit(); 
      editor.putString("Cookie", cook_new); 
      editor.commit(); 
     } 
    } 
    public void set_cookie(HttpURLConnection conn) { 
     SharedPreferences sh_pref_cookie = getSharedPreferences("cookies", Context.MODE_PRIVATE); 
     String COOKIES_HEADER = "Cookie"; 
     String cook = sh_pref_cookie.getString(COOKIES_HEADER, "no_cookie"); 
     if (!cook.equals("no_cookie")) { 
      conn.setRequestProperty(COOKIES_HEADER, cook); 
     } 
    } 

當然,您必須在異步線程中發送請求。

希望它有幫助。並原諒我的英語不好:)

,如果你想用你的java應用程序登錄
+0

美麗,終於登錄了!感謝您的時間和精力。像魅力:) – env

1

或android系統,那麼你需要嘗試與HTTPPOST

示例代碼:

public class HttpPostExample extends Activity { 

     TextView content; 
     EditText fname, email, login, pass; 
     String Name, Email, Login, Pass; 

     /** Called when the activity is first created. */ 
     @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_http_post_example); 

      content = (TextView)findViewById(R.id.content); 
      fname  = (EditText)findViewById(R.id.name); 
      email  = (EditText)findViewById(R.id.email); 
      login  = (EditText)findViewById(R.id.loginname); 
      pass  = (EditText)findViewById(R.id.password); 


      Button saveme=(Button)findViewById(R.id.save); 

      saveme.setOnClickListener(new Button.OnClickListener(){ 

       public void onClick(View v) 
       { 
        try{ 

          // CALL GetText method to make post method call 
          GetText(); 
        } 
        catch(Exception ex) 
        { 
         content.setText(" url exeption! "); 
        } 
       } 
      }); 
     } 

    // Create GetText Metod 
public void GetText() throws UnsupportedEncodingException 
     { 
      // Get user defined values 
      Name = fname.getText().toString(); 
      Email = email.getText().toString(); 
      Login = login.getText().toString(); 
      Pass = pass.getText().toString(); 

      // Create data variable for sent values to server 

      String data = URLEncoder.encode("name", "UTF-8") 
         + "=" + URLEncoder.encode(Name, "UTF-8"); 

      data += "&" + URLEncoder.encode("email", "UTF-8") + "=" 
         + URLEncoder.encode(Email, "UTF-8"); 

      data += "&" + URLEncoder.encode("user", "UTF-8") 
         + "=" + URLEncoder.encode(Login, "UTF-8"); 

      data += "&" + URLEncoder.encode("pass", "UTF-8") 
         + "=" + URLEncoder.encode(Pass, "UTF-8"); 

      String text = ""; 
      BufferedReader reader=null; 

      // Send data 
      try 
      { 

       // Defined URL where to send data 
       URL url = new URL("http://androidexample.com/media/webservice/httppost.php"); 

      // Send POST data request 

      URLConnection conn = url.openConnection(); 
      conn.setDoOutput(true); 
      OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
      wr.write(data); 
      wr.flush(); 

      // Get the server response 

      reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 

      // Read Server Response 
      while((line = reader.readLine()) != null) 
       { 
        // Append server response in string 
        sb.append(line + "\n"); 
       } 


       text = sb.toString(); 
      } 
      catch(Exception ex) 
      { 

      } 
      finally 
      { 
       try 
       { 

        reader.close(); 
       } 

       catch(Exception ex) {} 
      } 

      // Show response on activity 
      content.setText(text ); 

     } 

    } 

我是從這個網址獲得這個來源url你得到的所有東西都與你的查詢有關。

或者如果你想連接到* FTP登錄*那麼你可以按照婁代碼

import java.io.FileInputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.net.SocketException; 

import org.apache.commons.io.IOUtils; 
import org.apache.commons.net.ftp.FTP; 
import org.apache.commons.net.ftp.FTPClient; 

public class Ftpdemo { 


    public static void main(String args[]) { 

     // get an ftpClient object 
     FTPClient ftpClient = new FTPClient(); 
     ftpClient.setConnectTimeout(300); 
     FileInputStream inputStream = null; 

     try { 
     // pass directory path on server to connect 
     ftpClient.connect("ftp.mydomain.in"); 

     // pass username and password, returned true if authentication is 
     // successful 
     boolean login = ftpClient.login("myusername", "mypassword"); 

     if (login) { 
     System.out.println("Connection established..."); 
     ftpClient.setFileType(FTP.BINARY_FILE_TYPE); 

     ftpClient.enterLocalPassiveMode(); 

     inputStream = new FileInputStream("/home/simmant/Desktop/mypic.png"); 

     boolean uploaded = ftpClient.storeFile("user_screens/test3.png",inputStream); 



       if (uploaded) { 
     System.out.println("File uploaded successfully !"); 
     } else { 
     System.out.println("Error in uploading file !"); 
     } 

     // logout the user, returned true if logout successfully 
     boolean logout = ftpClient.logout(); 
     if (logout) { 
     System.out.println("Connection close..."); 
     } 
     } else { 
     System.out.println("Connection fail..."); 
     } 

     } catch (SocketException e) { 
     e.printStackTrace(); 
     } catch (IOException e) { 
     e.printStackTrace(); 
     } finally { 
     try { 
     ftpClient.disconnect(); 
     } catch (IOException e) { 
     e.printStackTrace(); 
     } 
     } 
    } 


    } 
相關問題