android - 通过 android webview 应用程序登录网络

标签 android http-post android-webview

我想使用 webview 构建一个 android 应用程序, 我希望 webview 应用程序使用我使用 http-post 方法发送的参数自动登录。 我引用了这个: Logging in via HttpPost to a website via an application

但仍然无法登录到我的网站,并且它总是显示登录表单,我应该将发布数据发送到: android.erfolgmedia.com/new_login/log.php?act=in 并通过 webview android 通过 http post 发送电子邮件和密码,

这是我的代码:

url = "http://android.erfolgmedia.com/new_login/log.php?act=in";
    String login_tag = "login";
    String email = "adi@erfolgmedia.com";
    String pass = "adiadi";

    try{
    List<NameValuePair> params2 = new ArrayList<NameValuePair>();
    params2.add(new BasicNameValuePair("tag", login_tag));
    params2.add(new BasicNameValuePair("email", email));
    params2.add(new BasicNameValuePair("password", pass));

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    httppost.setEntity(new UrlEncodedFormEntity(params2, HTTP.UTF_8));
    HttpResponse response = httpclient.execute(httppost);
    String data = new BasicResponseHandler().handleResponse(response);
    webView = (WebView) findViewById(R.id.webView1);

    webView.setWebViewClient(new HelloWebViewClient());
    webView.loadDataWithBaseURL(httppost.getURI().toString(), data, "text/html", HTTP.UTF_8, null);
    webView.getSettings().setJavaScriptEnabled(true);

    String postData = "tag" + "=" + login_tag + "&" + "email" + "=" + email + "&" + "password" + "=" + pass;

    webView.postUrl(url, EncodingUtils.getBytes(postData, "utf-8"));
    }catch(Exception e){
        e.printStackTrace();
    }

    //openBrowser();
}

感谢您的宝贵时间!非常感谢您能百忙之中查看我的问题。

最佳答案

我曾经上过下面的课。我不知道它是否是最新的,所以你可能需要稍微调整一下。您可以使用以下方式调用它:

RestWrapperAsync wrapper = new RestWrapperAsync();  
wrapper.SetUp("url");
wrapper.setFormBodyJson(jsonArray); //or setform..
wrapper.SetAuthentication("name", "password");
wrapper.SetResponseCallback(this);
wrapper.execute();

public class RestWrapperAsync  extends AsyncTask<Void, Integer, Object> {

    private WeakReference<ResponseCallback> mResponseCallback;
    private WeakReference<ProgressCallback> mProgressCallback;

    public interface ResponseCallback {
        public void OnRequestSuccess(String response);
        public void OnRequestError(Exception ex);
    }

    public interface ProgressCallback {
        public void OnProgressUpdate(int progress);
    }

    public void SetResponseCallback(ResponseCallback callback){
        mResponseCallback = new WeakReference<ResponseCallback>(callback);
    }

    public void setProgressCallback(ProgressCallback callback) {
        mProgressCallback = new WeakReference<ProgressCallback>(callback);
    }   

    private boolean getDetailsFromPost = false;

    public void SetGetDetailsFromPost(boolean value){
        getDetailsFromPost = value;
    }

    HttpURLConnection mConnection;
    String mFormBody;
    File mUploadFile;
    String mUploadFileName;
    JSONArray mFormBodyJSONArray;
    JSONObject mFormBodyJSON;

    /**
     * Sets up the connection and the url
     * @param siteUrl
     */
    public void SetUp(String siteUrl, boolean doOutput){
        try
        {
            URL url=null;   
            if (siteUrl!=null) {
                url = new URL(siteUrl);
            }
            else {
                url = new URL("https://xxxx");
            }
            mConnection = (HttpURLConnection) url.openConnection();
            mConnection.setReadTimeout(10000 /* milliseconds */);
            mConnection.setConnectTimeout(5000 /* milliseconds */);
            mConnection.setRequestMethod("GET"); //set to get initially

            if (doOutput){
                //mConnection.setDoOutput(true);
                mConnection.setDoInput(true);
            }
            else
                mConnection.setDoInput(true);
        }
        catch (Exception ex){
            Log.e("ERROR","Exception setting up connection:"+ex.getMessage());
        }
    }

    /**
     * Sets up form body for post requests
     * @param formData
     */
    public void setFormBody(List<NameValuePair> formData){
        if (formData == null) {
            mFormBody = "";
            return;
        }
        try
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < formData.size(); i++) {
                NameValuePair item = formData.get(i);
                sb.append( URLEncoder.encode(item.getName(),"UTF-8") );
                sb.append("=");
                sb.append( URLEncoder.encode(item.getValue(),"UTF-8") );
                if (i != (formData.size() - 1)) {
                    sb.append("&");
                }
            }
            mFormBody = sb.toString();
        }
        catch(Exception ex){
            Log.e("ERROR","Exception setting up connection:"+ex.getMessage());
        }
    }

    /**
     * Sets up form body for post request
     * @param object
     */
    public void setFormBodyJson(JSONArray object){
        mFormBodyJSONArray = object;
    }

    /**
     * Sets up form body for post request
     * @param object
     */
    public void setFormBodyJson(JSONObject object){
        mFormBodyJSON = object;
    }

    /**
     * Write out Json array to outputstream
     * @param charset
     * @param output
     * @throws IOException
     */
    private void writeFormDataJSON(JSONArray charset, OutputStream output) throws IOException {
        try 
        {
            output.write(charset.toString().getBytes());
            output.flush();
        } 
        finally 
        {
            if (output != null) {
                output.close();
            }
        }
    }   

    /**
     * Write out Json object to outputstream
     * @param charset
     * @param output
     * @throws IOException
     */
    private void writeFormDataJSON(JSONObject charset, OutputStream output) throws IOException {
        try 
        {
            output.write(charset.toString().getBytes());
            output.flush();
        } 
        finally 
        {
            if (output != null) {
                output.close();
            }
        }
    }

    /**
     * Write out Charset to outputStream
     * @param charset
     * @param output
     * @throws IOException
     */
    private void writeFormData(String charset, OutputStream output) throws IOException {
        try 
        {
            output.write(mFormBody.getBytes(charset));
            output.flush();
        } 
        finally 
        {
            if (output != null) {
                output.close();
            }
        }
    }   

    /**
     * Sets up authentication
     * @param username
     * @param password
     */
    public void SetAuthentication(String username, String password){
        if (this.mConnection==null) {
            Log.e("RestWrapper","Autentication called, but connection = null");
        }
        else
            attachBasicAuthentication(mConnection,username,password); 
    }

    /**
     * Attaches authorization to header
     * @param connection
     * @param username
     * @param password
     */
    private static void attachBasicAuthentication(URLConnection connection, String username, String password) {
        //Add Basic Authentication Headers
        String userpassword = username + ":" + password;
        String encodedAuthorization =
            Base64.encodeToString(userpassword.getBytes(), Base64.NO_WRAP);
        connection.setRequestProperty("Authorization", "Basic "+ encodedAuthorization);
    }

    public void setUploadFile(File file, String fileName) {
        mUploadFile = file;
        mUploadFileName = fileName;
    }

    /**
     * Do network connection in background
     */
    @Override
    protected Object doInBackground(Void... arg0) {
        return CallService(true);
    }

    /**
     * The actual call to the web api's
     * @param isAsyn
     * @return
     */
    public Object CallService(boolean isAsyn){
        try
        {
            String charset = Charset.defaultCharset().displayName();

            if (mFormBodyJSON != null) {
                mConnection.setDoOutput(true);
                mConnection.setRequestMethod("POST");
                mConnection.setRequestProperty("Content-Type","application/json; charset="+charset);
                mConnection.setFixedLengthStreamingMode(mFormBodyJSON.toString().length());
            }
            else if (mFormBodyJSONArray != null) {
                mConnection.setDoOutput(true);
                mConnection.setRequestMethod("POST");
                mConnection.setRequestProperty("Content-Type","application/json; charset="+charset);
                mConnection.setFixedLengthStreamingMode(mFormBodyJSONArray.toString().length());
            }
            else if (mFormBody != null) {
                mConnection.setDoOutput(true);
                mConnection.setRequestMethod("POST"); //change to post
                mConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset="+charset);
                mConnection.setFixedLengthStreamingMode(mFormBody.length());
            }

            if (isAsyn)
                this.publishProgress(1);

            mConnection.connect();

            if (mFormBodyJSON!=null){
                OutputStream out = mConnection.getOutputStream();
                writeFormDataJSON(mFormBodyJSON, out);  
            }
            else if (mFormBodyJSONArray!=null){
                OutputStream out = mConnection.getOutputStream();
                writeFormDataJSON(mFormBodyJSONArray, out); 
            }           
            else if (mFormBody != null) {
                OutputStream out = mConnection.getOutputStream();
                writeFormData(charset, out);    
            }

            int status=0;
            status = mConnection.getResponseCode();

            if (isAsyn)
                this.publishProgress(2);

            if (status == 204){
                if (!getDetailsFromPost){
                    return Constants.DATAPOSTEDCORRECTLY;
                }
            } 

            if (status >= 300){
                String message = mConnection.getResponseMessage();

                InputStream in = mConnection.getErrorStream();
                String encoding = mConnection.getContentEncoding();
                if (encoding == null) {
                    encoding = "UTF-8";
                }
                if (in != null) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in, encoding));
                    message = reader.readLine();
                    message = message.replace('"', ' ');
                    message = message.trim();
                    return new HttpResponseException(status, message);
                }
            }

            //Get response data back
            InputStream in = mConnection.getInputStream();
            String encoding = mConnection.getContentEncoding();

            if (encoding == null) {
                encoding = "UTF-8";
            }

            this.publishProgress(3);

            BufferedReader reader = new BufferedReader(new InputStreamReader(in, encoding));
            String result = reader.readLine();
            return result;
        }
        catch (Exception ex){
            return ex;
        }
        finally {
            if (mConnection != null) {
                mConnection.disconnect();
            }
        }
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        if (mProgressCallback != null && mProgressCallback.get() != null) {
            mProgressCallback.get().OnProgressUpdate(values[0]);
        }
    }

    @Override
    protected void onPostExecute(Object result) {
        if (mResponseCallback != null && mResponseCallback.get() != null) {
            if (result instanceof String) {
                mResponseCallback.get().OnRequestSuccess((String) result);
            } 
            else if (result instanceof Exception) {
                mResponseCallback.get().OnRequestError((Exception) result);
            } 
            else {
                mResponseCallback.get().OnRequestError(new IOException("Unknown Error Contacting Host"));
            }

            mResponseCallback = null;
            mProgressCallback = null;
        }
    }
}

关于android - 通过 android webview 应用程序登录网络,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23340715/

相关文章:

android - TextView 在不同的分辨率下具有不同的高度。 DIP 不起作用

html - 在 HTML <form> 中 POST 额外值

android - 如何在 android 中使用 Google Place Check-Ins

android - 在android中添加动态网页 View

android - 如何从url下载pdf并在android应用程序本身中查看下载的pdf?

android - onStop 在 onDestroy 之后被调用?

java - 解析 JSON 数据时出错 - 异步任务

android - 当我更改语言环境时字体不同?

java - 如何将 HTTP 发布到 CGI 脚本

html - Android 4.2.2 的 WebView (Webkit 534.30) 支持什么?