当前位置: 首页 > 知识库问答 >
问题:

在AsyncTask中通过REST进行简单的HTTP登录

房唯
2023-03-14

我不熟悉编程和Android,这是我第一次尝试编程一个应用程序,但我已经无法登录了。登录必须与服务器连接,在get请求的帮助下,我将获得json数据,我可以使用它来验证登录数据(用户名)。允许使用该应用程序的人员已在数据库中。这应该很简单。在这个论坛中,我只能找到使用HTTPClient等的解决方案,但仅使用HTTPURLConnection已不再有效。我使用了LoginActivity模板

这是我的代码(我也没有使用JSON数据的经验)。这是我们的JSON数据结构:

{
  "id": "1234",
  "firstName": "xx",
  "lastName": "xy",
  "fullName": "xx xy"
}

public class UserLoginTask extends AsyncTask<String, Void, Boolean> {

    private final String mEmail;
    private final String mPassword;

    UserLoginTask(String email, String password) {
        mEmail = email;
        mPassword = password;
    }

    @Override
    protected Boolean doInBackground(String... params) {

       final String REQUEST_METHOD = "GET";
       final int READ_TIMEOUT = 15000;
       final int CONNECTION_TIMEOUT = 15000;
        // attempt authentication against a network service.
        //InputStream is;


        URL url = null;
        try {
            String username = params[0];
            String password = params[1];
            String inputLine;
            String result;

            url = new URL("URL//");
            //Connection with database
            urlConnection=(HttpURLConnection) url.openConnection();
            //Connect with database
            //urlConnection.connect();
            //Open stream;
            //is=urlConnection.getInputStream();

            //Set methods and timeouts
            urlConnection.setRequestMethod(REQUEST_METHOD);
            urlConnection.setReadTimeout(READ_TIMEOUT);
            urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);

            //Connect to our URL
            urlConnection.connect();

            //TODO
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoInput(true);

            //Create a new InputStreamReader
            InputStreamReader streamReader = new
                    InputStreamReader(urlConnection.getInputStream());
            //Create a new buffered reader and String Builder
            BufferedReader reader = new BufferedReader(streamReader);
            StringBuilder stringBuilder = new StringBuilder();

            //Check if the line we are reading is not null
            while((inputLine = reader.readLine()) != null){
                stringBuilder.append(inputLine);
            }

            //Close our InputStream and Buffered reader
            reader.close();
            streamReader.close();

            //Set our result equal to our stringBuilder
            result = stringBuilder.toString();

            //Proceed in function of status code response
            int status = urlConnection.getResponseCode();

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

    return false;

        /*for (String credential : DUMMY_CREDENTIALS) {
            String[] pieces = credential.split(":");
            if (pieces[0].equals(mEmail)) {
                // Account exists, return true if the password matches.
                return pieces[1].equals(mPassword);
            }
        }

        // TODO: register the new account here.
        return true;*/
    }

    @Override
    protected void onPostExecute(final Boolean success) {
        mAuthTask = null;
        showProgress(false);

        if (success) {
            finish();
        } else {
            mPasswordView.setError(getString(R.string.error_incorrect_password));
            mPasswordView.requestFocus();
        }
    }

我在Http服务类中也有这个:我的类httpservice中有这些方法:我如何使用这个?

private HttpURLConnection setup connection(String URL,Credentials credentials)抛出io exception { URL reqUrl = new URL(URL);HttpURLConnection URL connection =(HttpURLConnection)requrl . open connection();

    if (credentials != null && !credentials.getPassword().isEmpty() && !credentials.getUsername().isEmpty()) {
        urlConnection.setRequestProperty("Authorization", createBasicAuthString(credentials.getUsername(), credentials.getPassword()));
    }
    return urlConnection;
}


/**
 * Creates the String for the Authorization Header
 *
 * @param user
 * @param password
 * @return
 */
private String createBasicAuthString(String user, String password) {
    String notEncoded = user + ":" + password;
    String encodedAuth = Base64.encodeToString(notEncoded.getBytes(), Base64.DEFAULT);
    return "Basic " + encodedAuth;
}

共有1个答案

柴坚诚
2023-03-14

像这样解析您的JSON数据,

 JSONObject jsonObject = new JSONObject(Your_Sring_data);
 String  id= jsonObject.getJsonString("id");
 String firstName= jsonObject.getJsonString("firstName");
 String lastName= jsonObject.getJsonString("lastName");
 String fullName= jsonObject.getJsonString("fullName");

并返回响应字符串,而不是doInBackground()方法中的布尔成功变量,并通过上述代码解析该字符串

 类似资料:
  • 问题内容: 一些背景: 我正在尝试在android应用程序上开发与语音相关的功能,用户可以在其中使用语音进行搜索,并且服务器在用户讲话时会发送中间结果(依次更新UI),并在查询完成后发送最终结果。由于服务器仅接受HTTP / 2单套接字连接,而Android HTTPUrlConnection 尚不支持 HTTP / 2,因此我正在使用Retrofit2。 我已经看过了这个,这个和这个,但是每个示

  • 我们目前正在从遗留安全子系统迁移到Elytron,并在JBoss EAP 7.3.6中部署了一个基于Struts2的web应用程序,该应用程序应该支持多种“风格”的身份验证。 登录的标准方式应该是,用户以登录表单()手动提供凭据,然后单击相应的按钮。这在我们的设置中与Elytron配合得很好。 第二种可能性是,对Web应用程序受保护内容的GET请求可能包含包含JWT令牌的自定义cookie。这个c

  • 问题内容: 通过AJAX从标准HTTP页面调用HTTPS页面(例如信用卡授权服务,例如WorldPay)是否会有问题? 我无法想象为什么会有问题,响应将是HTML页面,然后我可以将其嵌入结果窗格或类似的页面? 问题答案: 是的,这将是跨域发布,并且将被浏览器阻止。

  • 我正在尝试使用PayPal REST API来处理使用银行帐户和路由号码的银行交易。 以下是我用于测试的 api 的引用:https://api.sandbox.paypal.com/v1/payments/payment 这是我的JSON: 以下是调用的响应:“{\”name\":\"NOT_IMPLEMENTED\"、\"消息\":\"NOT_IMPLEMENTED\"、\"informati

  • 我正在尝试在javascript中自定义一个可以通过REST调用访问的endpoint。此终结点处理与不同情况相关的多个条件(基本上它生成一次性密码,然后验证它以检查它是否过期等)。 所以基本上结构是这样的: 我在开始时设置了一个对象,然后映射一个json消息,以便检索具有不同代码/消息响应的正文。因此,当终结点输入这些条件时,它将返回对象,并且 Header 始终为 200(调用成功)。像这样:

  • 我正在尝试使用Spring Security UserDetailService身份验证使用电子邮件而不是用户名登录,但我无法登录并获取 org.springframework.security.authentication.内部身份验证服务异常。 调试代码时,调试器不会跟踪 用户user=userDao。findByUserName(用户电子邮件);来自UserServiceImpl。java和