Java Android:如何以编程方式登录网站并从中检索数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22717806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:27:41  来源:igfitidea点击:

Android: How to programatically login to website and retrieve data from it?

javaandroidposthttpclienthttpurlconnection

提问by emilancius

Ok, guys, so I'm recently developing android app that saves user's ID and PASSWORD to SharedPreferences. Now, when the user starts app second time, he will be redirected directly to MainActivity with a few options in listView. And now I have a huge headache and it's driving me REAL crazy. I cannot login to website and fetch the data to my phone. I've tried using Http(s)UrlConnection, HttpClient, but it just doesn't seem to work for me. All I get from POST method is a source code of login page.

好的,伙计们,所以我最近正在开发将用户 ID 和密码保存到 SharedPreferences 的 android 应用程序。现在,当用户第二次启动应用程序时,他将被直接重定向到 MainActivity,并在 listView 中有几个选项。现在我头疼得厉害,这让我真的发疯了。我无法登录网站并将数据提取到我的手机。我试过使用 Http(s)UrlConnection、HttpClient,但它似乎对我不起作用。我从 POST 方法中得到的只是登录页面的源代码。

Now, there is login page: https://medeine.vgtu.lt/studentams/login.jsp?klb=en

现在,有登录页面:https: //medeine.vgtu.lt/studentams/login.jsp?klb=en

and my target page: https://medeine.vgtu.lt/studentams/pask_stud.jsp<-- I need to fetch data from there

和我的目标页面:https: //medeine.vgtu.lt/studentams/pask_stud.jsp<--我需要从那里获取数据

Have you got any thoughts or tips/methods/guides/anything how to do that?

你有任何想法或技巧/方法/指南/任何如何做到这一点吗?

采纳答案by Constantine

For this you must send two POST requests. In first request, you need send login data and save cookies, if success login. In second request, need send saved cookies and you can get the data. Data for POST must be formatted like this: var=value&var2=value2

为此,您必须发送两个 POST 请求。在第一个请求中,如果登录成功,您需要发送登录数据并保存 cookie。在第二个请求中,需要发送保存的 cookie 才能获取数据。POST 的数据格式必须是这样的:var=value&var2=value2

In your case:

在你的情况下:

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

And url for request: https://medeine.vgtu.lt/studentams/submit.jsp

和请求网址:https: //medeine.vgtu.lt/studentams/submit.jsp

Look following code:

看下面的代码:

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

Of course you must send requests in async thread.

当然,您必须在异步线程中发送请求。

Hope it helpful. And excuse me for my bad english:)

希望有帮助。请原谅我的英语不好:)

回答by Simmant

if you want to login with the you application in java or in android then you need to try with HTTPPOST

如果您想使用 java 或 android 中的应用程序登录,则需要尝试使用 HTTPPOST

example code:

示例代码:

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

      }

  }

i am getting this source from this urlin this url you get all thing related your query.

我从这个url中的这个 url得到这个源,你得到所有与你的查询相关的东西。

or If you want to connect to the *FTP Login *then you can follow bellow code

或者如果你想连接到 * 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();  
       }  
      }  
     }


    }