Android利用HttpURLConnection實現模擬登陸

  最近在作一個APP,須要模擬登陸教務處,以前曾經用HttpClient作過,點這裏,可是發現最新的Android SDK已經不支持Httpclient了,因此只好在琢磨一下HttpURLConnection實現了,其中一個問題浪費了很多時間,下面這行代碼一旦添加就沒法登陸:html

httpURLConnection.setRequestProperty("Content-Type","text/html; charset=GBK");

  貼一下效果,因爲是實現模擬登陸,就沒有解析,主要是能用Cookie訪問到。java

  此外,有一個重要發現,用電腦和手機對應的Cookie都能登陸,說明服務器能夠對應多個Cookie!android

  真是一路磕磕絆絆!git

  貼下主要代碼:github

  1.結構服務器

  

 

  2.MainActivitycookie

package io.github.zhaoyu1995.uprtest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private TextView kebiao;
    private MyTasks task;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        kebiao = (TextView) findViewById(R.id.kebiao);
        task = new MyTasks("201445004", "******", new OnFinishTask() {
            @Override
            public void onFinish(String data) {
                kebiao.setText(data);
            }
        });
        task.execute();
    }



}
View Code

  3.MyTaskapp

package io.github.zhaoyu1995.uprtest;

import android.os.AsyncTask;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


public class MyTasks extends AsyncTask<Void, Void, String> {
    private OnFinishTask onFinishTask;
    private String user;
    private String pass;
    private String result;

    private List<String> finalCookie = new ArrayList<String>();
    private String jiaowuchu = "http://zhjw.dlut.edu.cn/loginAction.do";
    public MyTasks (String user, String pass, OnFinishTask onFinishTask) {
        this.user = user;
        this.pass = pass;

        this.onFinishTask = onFinishTask;
    }

    @Override
    protected String doInBackground(Void... voids) {
        URL url;
        HttpURLConnection httpURLConnection;

        try {
            url = new URL(jiaowuchu);
            httpURLConnection = (HttpURLConnection) url.openConnection();

            httpURLConnection.setDoOutput(true);//是否向連接輸出
            httpURLConnection.setDoInput(true);

            httpURLConnection.setRequestMethod("POST");

            httpURLConnection.setUseCaches(false);
            httpURLConnection.setInstanceFollowRedirects(true);

            //不知道爲何加了這一行就不行了
            httpURLConnection.setRequestProperty("Content-Type","text/html; charset=GBK");
            httpURLConnection.setConnectTimeout(10*1000);//鏈接超時 單位毫秒
            httpURLConnection.setReadTimeout(10*1000);//讀取超時 單位毫秒

            // 鏈接,從postUrl.openConnection()至此的配置必需要在connect以前完成,
            // 要注意的是connection.getOutputStream會隱含的進行connect。
            httpURLConnection.connect();
            DataOutputStream out = new DataOutputStream(httpURLConnection
                    .getOutputStream());


            StringBuffer params = new StringBuffer();
            params.append("zjh").append("=").append(user).append("&")
                    .append("mm").append("=").append(pass);
            httpURLConnection.getOutputStream().write(params.toString().getBytes("gb2312"));
            out.flush();
            out.close();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    httpURLConnection.getInputStream(), "gb2312"));
            String line;
            while ((line = reader.readLine()) != null) {
                result = result + line;
            }
            reader.close();

            result="";
            Map<String, List<String>> header = httpURLConnection.getHeaderFields();
            List<String> cookies = header.get("Set-Cookie");
            Iterator<String> it = cookies.iterator();
            StringBuffer sbu = new StringBuffer();
        //  sbu.append("eos_style_cookie=default; ");
            while(it.hasNext()){
                sbu.append(it.next());
            }

            result = cookies.size()+"";

            for (int i = 0; i < cookies.size(); i++) {
                finalCookie.add(cookies.get(i));
            }

            result = result+finalCookie.get(0);
            result = result+"--------------"+finalCookie.get(1);

            httpURLConnection.disconnect();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //get課表

        try {
            url = new URL("http://zhjw.dlut.edu.cn/xkAction.do?actionType=6");
            httpURLConnection = (HttpURLConnection) url.openConnection();
            //必要的設置
            httpURLConnection.setConnectTimeout(10*1000);//鏈接超時 單位毫秒
            httpURLConnection.setReadTimeout(10*1000);//讀取超時 單位毫秒
            httpURLConnection.setRequestProperty("Cookie", finalCookie.get(0)+", "+finalCookie.get(1));
            System.out.println(finalCookie.get(0)+", "+finalCookie.get(1));
//            httpURLConnection.setRequestProperty("Cookie", "JSESSIONID=nprNP171vDeCHb_5hawDv; path=/, NSC_kjbpxv-iuuq=2385a3d4705debd5f29101f47dcbd3b0e664f181853b4741569229a0561453d027e6fa67;path=/");
            httpURLConnection.connect();
            BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "gb2312"));
            String lines;
            //result = "";
            while ((lines = reader.readLine()) != null) {
                result = result + lines;
            }
            reader.close();
            // 斷開鏈接
            result = result + httpURLConnection.getResponseCode();
            httpURLConnection.disconnect();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        onFinishTask.onFinish(s);
    }
}
View Code

  4.OnFinishTaskide

package io.github.zhaoyu1995.uprtest;


public interface OnFinishTask {
    public void onFinish(String data);
}
View Code
相關文章
相關標籤/搜索