【问题标题】:Android HttpUrlConnection and specific site loggingAndroid HttpUrlConnection 和特定站点日志记录
【发布时间】:2013-06-21 00:17:19
【问题描述】:

谁能帮助我编写一个程序来连接到站点、登录并获取登录站点的内容?我希望它适用于网站http://www.imperiaonline.org 有很多重定向和 POST 请求,我不知道是否可能。请帮帮我。

我尝试过类似的方法,但它不起作用......

    dateFormat = new SimpleDateFormat(DATE_FORMAT);
    store = new ArrayList<Map<String, String>>();

    String uRL = "http://www.imperiaonline.org";

    StringBuilder response = new StringBuilder();
    Log.v("Execute", "execute url:" + uRL);
    try {
        URL url = new URL(uRL);
        HttpURLConnection httpconn = (HttpURLConnection) url
                .openConnection();

        if (sCookie != null && sCookie.length() > 0) {
            httpconn.setRequestProperty("Cookie", sCookie);
        }

        if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            BufferedReader input = new BufferedReader(
                    new InputStreamReader(httpconn.getInputStream()), 8192);
            String strLine = null;
            while ((strLine = input.readLine()) != null) {
                response.append(strLine);
            }
            input.close();
        }

        String headerName = null;
        for (int i = 1; (headerName = httpconn.getHeaderFieldKey(i)) != null; i++) {
            if (headerName.equalsIgnoreCase(SET_COOKIE)) {
                Map<String, String> cookie = new HashMap<String, String>();
                StringTokenizer st = new StringTokenizer(
                        httpconn.getHeaderField(i), COOKIE_VALUE_DELIMITER);

                // the specification dictates that the first name/value pair
                // in the string is the cookie name and value, so let's
                // handle
                // them as a special case:

                if (st.hasMoreTokens()) {
                    String token = st.nextToken();
                    String name = token.substring(0,
                            token.indexOf(NAME_VALUE_SEPARATOR));
                    String value = token.substring(
                            token.indexOf(NAME_VALUE_SEPARATOR) + 1,
                            token.length());
                    store.add(cookie);
                    cookie.put(name, value);
                }

                while (st.hasMoreTokens()) {
                    String token = st.nextToken();
                    cookie.put(
                            token.substring(0,
                                    token.indexOf(NAME_VALUE_SEPARATOR))
                                    .toLowerCase(),
                            token.substring(
                                    token.indexOf(NAME_VALUE_SEPARATOR) + 1,
                                    token.length()));
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    for (int i = 0; i < store.size(); ++i) {
        for (String element : store.get(i).keySet()) {
            Log.i("ARR", element);
        }
    }
    Log.i("HTML", response.toString());


    try {
        StringBuilder postDataBuilder = new StringBuilder().append("uname=").append(URLEncoder.encode("zygmunter", "UTF8"));
        postDataBuilder.append("password=").append(URLEncoder.encode("zygmunter", "UTF8"));
        byte[] postData = null;
        postData = postDataBuilder.toString().getBytes();

        URL url = new URL("http://www99.imperiaonline.org/imperia/game_v5/game/ajax_login.php");
        HttpURLConnection co = (HttpURLConnection) url.openConnection();

        co.setDoOutput(true);
        co.setRequestMethod("POST");
        co.setRequestProperty("Content-Length", Integer.toString(postData.length));
        co.setUseCaches(false);

        OutputStream out = co.getOutputStream();
        out.write(postData);
        out.close();

        response = new StringBuilder();
        if (co.getResponseCode() == HttpURLConnection.HTTP_OK) {
            BufferedReader input = new BufferedReader(
                    new InputStreamReader(co.getInputStream()), 8192);
            String strLine = null;
            while ((strLine = input.readLine()) != null) {
                response.append(strLine);
            }
            input.close();
        }
        String resp = response.toString();
        Log.i("WYNIK", resp);
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

【问题讨论】:

    标签: android


    【解决方案1】:

    看看this 的例子。

    private HttpClient mHttpClient;
    private HttpContext mContext;
    private CookieStore mCookieStore;
    
    public void post(){
            ArrayList<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
            list.add(new BasicNameValuePair("uname", "your username"));
            list.add(new BasicNameValuePair("password", "your username"));
            list.add(new BasicNameValuePair("form_submit", "Login"));
            task mTask = new task();
            mTask.execute(list);
        }
        public class task extends AsyncTask<ArrayList<BasicNameValuePair>, Void, String>{
    
            @Override
            protected String doInBackground(ArrayList<BasicNameValuePair>... arg0) {
                if(mHttpClient == null){
                   mHttpClient = new DefaultHttpClient();
                 }
                 if(mContext == null){
                    mContext = new BasicHttpContext();
                 }
                 if(mCookieStore == null){
                     mCookieStore = new BasicCookieStore();
                 }
                mContext.setAttribute(ClientContext.COOKIE_STORE, mCookieStore)
                String sResponse = "";
                HttpResponse response = null;
                try{
    
                    HttpPost httppost = new HttpPost("http://www99.imperiaonline.org/imperia/game_v5/game/ajax_login.php");
                    httppost.setEntity(new UrlEncodedFormEntity(arg0[0]));
                    mHttpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
                    response = mHttpClient.execute(httppost, mContext);
                    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                    StringBuilder s = new StringBuilder();
                    while ((sResponse = reader.readLine()) != null) {
                        s = s.append(sResponse);
                    }
    
                    // Getting cookies 
                    ArrayList<Cookie> list = new ArrayList<Cookie>(mCookieStore.getCookies());
                    for(Cookie cookie : list){
                       Log.i(TAG, "cookie: " + cookie.getName());
                    }
                }catch(IOException e){
    
                }
                return sResponse;
            }
    
            @Override 
            protected void onPostExecute(String result){
                System.out.println(result);
            }
    
        }
    

    【讨论】:

    • 你有没有注意到在 post 请求中还有参数 auth 我找不到它来自哪里...
    • 作为响应,我只得到带有重定向的简单 javascript。我想我必须从登录页面收集 cookie,使用此帖子请求登录,然后使用收集的 cookie 获取我收到重定向到的页面内容。我对吗?抱歉问了这么一个讨厌的问题,但饼干之类的东西对我来说总是很神奇;)也许你知道任何解释它们的好页面。
    • 您好,cookie 存储在 mCookieStore 中。我修改了代码以显示如何从 cookiestore 获取 cookie 值。这里还有另一种获取cookie的方法:stackoverflow.com/a/8133462/1888162这里也是有用的信息:svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/…
    猜你喜欢
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2016-08-01
    • 2020-03-19
    • 1970-01-01
    相关资源
    最近更新 更多