无法从网页上获取Cookie,这就是我无法访问其内容的原因

时间:2013-12-06 06:30:35

标签: java android asp.net cookies

我正在编写一个Android项目,它现在仍在进行大约5个月。我正在开发的应用程序将允许用户从我们的公司网页http://www.allianceinmotion.com/members.asp登录并浏览其个人帐户的内容。

我刚接触编程(0经验),我在开发这个应用程序时遇到很多问题。

问题#1。如何获取json数据响应?我正在查看浏览器的开发者工具,但我不知道我在哪里可以找到我们公司网页的必要信息。

问题#2。我无法通过logcat从我们公司的网页上获取cookie。

问题#3。即使登录/密码正确,我也只能看到我们的登录网页,但不能看到我帐户的内容。

问题#4。我不确定我应该在WebView类(MyAccounts.class)上放置什么URL。

  • 请帮我纠正我的代码或插入一些额外的代码。

以下是我的代码:

LoginActivity.java:

imports....

public class LoginActivity extends Activity implements OnClickListener {

   private ProgressDialog pDialog; // Progress Dialog
   private static final String LOGIN_URL = "http://vo.aimglobalinc.com/control/con_login.asp";
   JSONParser jsonParser = new JSONParser();

private EditText user, pass;
private Button mSubmit, mRegister;

// <....>

class AttemptLogin extends AsyncTask<String, String, String> {

            boolean failure = false;


            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(LoginActivity.this);
                pDialog.setMessage("Attempting to login...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();

            }
            @Override
            protected String doInBackground(String... args) {
                //BufferedReader in = null;
                try {
                         String username = user.getText().toString();
                    String password = pass.getText().toString();


                    // Building Parameters
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("uname", username));
                    params.add(new BasicNameValuePair("pword", password));

                            Log.d("request!", "starting");
                    // getting product details by making HTTP request
                    JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
                    // check your log for json response
                    Log.d("Login attempt", json.toString());
                            return json.getString("success");

                } catch (JSONException e) {
                    e.printStackTrace();
                } 


                return null;


            }

protected void onPostExecute(String result) {
                super.onPostExecute(result);
                //JSONObject json;
                // dismiss the dialog once product deleted
                pDialog.dismiss();

                if (result.equals("true")) {
                    //Toast.makeText(LoginActivity.this, "Login Successful!", Toast.LENGTH_SHORT).show();
                    Toast.makeText(LoginActivity.this, "Login Successful!", Toast.LENGTH_LONG).show();
                    Intent i = new Intent(LoginActivity.this, MyAccounts.class);
                    finish();
                    startActivity(i);   
                } else {
                    Toast.makeText(LoginActivity.this, "Please enter the correct username and password.", Toast.LENGTH_LONG).show();

                }

            }


        }

}

JSONParser.java

imports....


public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(final String url) {
    // Making HTTP request
    try {
        // Construct the client and the HTTP request.
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        // Execute the POST request and store the response locally.
        HttpResponse httpResponse = httpClient.execute(httpPost);
        // Extract data from the response.
        HttpEntity httpEntity = httpResponse.getEntity();
        // Open an inputStream with the data content.
        is = httpEntity.getContent();


    }catch (UnsupportedEncodingException e) {
        e.printStackTrace();

    }catch (ClientProtocolException e) {
        e.printStackTrace();

    }catch (IOException e) {
        e.printStackTrace();
    }
    try {
        // Create a BufferedReader to parse through the inputStream.
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        // Declare a string builder to help with the parsing.
        StringBuilder sb = new StringBuilder();
        // Declare a string to store the JSON object data in string form.
        String line = null;

        // Build the string until null.
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");

        }
        // Close the input stream
        is.close();
        // Convert the string builder data to an actual string.
        json = sb.toString();
    }catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());

    }
    // Try to parse the string to a JSON object
    try {
        jObj = new JSONObject(json);

    }catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());

    }
    // Return the JSON Object.
    return jObj;

}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,List<NameValuePair> params) {
    // Making HTTP request

    try {
        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            //List<Cookie> 
            List<Cookie> cookies = httpClient.getCookieStore().getCookies();
            if (cookies.isEmpty()) {
                Log.e("COOKIES post: ",  "Empty Cookies");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    Log.e("COOKIES post: ", cookies.get(i).getName()+"--"+ cookies.get(i).getValue());
                }
            }

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

               //List<Cookie> 
            List<Cookie> cookies = httpClient.getCookieStore().getCookies();
            if (cookies.isEmpty()) {
                Log.e("COOKIES post: ",  "Empty Cookies");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    Log.e("COOKIES post: ", cookies.get(i).getName()+"--"+ cookies.get(i).getValue());
                }
            }
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }
    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
    // return JSON String
    return jObj;

}

}

MyAccounts.java - (这是用户可以看到他/她帐户内容的类)

imports...


public class MyAccounts extends Activity {


WebView myWebView;

private final static String TAG = "WebView";

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_my_accounts);

    myWebView = (WebView) findViewById(R.id.webView1);

            new WebViewTask().execute();
    }

    private class WebViewTask extends AsyncTask<Void, Void, Boolean> {
    String sessionCookie;
    CookieManager cookieManager;

        @Override
    protected void onPreExecute() {
        CookieSyncManager.createInstance(MyAccounts.this);
        cookieManager = CookieManager.getInstance();


        if (sessionCookie != null) {
                            /* delete old cookies */
            cookieManager.removeSessionCookie(); 
        }
        super.onPreExecute();
    }
    protected Boolean doInBackground(Void... param) {

        SystemClock.sleep(1000);
        return false;
    }
    @Override
    protected void onPostExecute(Boolean result) {
        if (sessionCookie != null) {
            cookieManager.setCookie("http://vo.aimglobalinc.com/r2bs.asp", sessionCookie);
            CookieSyncManager.getInstance().sync();
        }
        WebSettings webSettings = myWebView.getSettings();
        //webSettings.setJavaScriptEnabled(true);
        webSettings.setBuiltInZoomControls(true);
        myWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return super.shouldOverrideUrlLoading(view, url);
            }

        });
        myWebView.loadUrl("http://vo.aimglobalinc.com/r2bs.asp");
    }
}
}

0 个答案:

没有答案