如何在OkHttp中保持连接活动或维护会话

时间:2018-01-17 15:40:04

标签: java android okhttp

我在服务器上有一个Web服务,并从android应用程序注册用户我首先向它发出POST请求以创建注册会话,然后向其发出包含表单数据的另一个POST请求。它使用内置的HttpsURLConnection工作正常,现在我开始使用OkHttp;服务器以不同的方式处理每个请求,就像它们来自两个不同的设备一样。如何维护我的第一个连接并向其发出另一个请求?我试图用邮递员提出请求,它也按预期工作。我首先对这样的网址进行空白的帖子调用:

https://mywebsite/api/user/register/start
,然后第二次请求使用表单参数
https://mywebsite/api/user/register
这样的网址以防万一有人想要查看我之前和当前的代码:
我以前的代码

    public void register(Context context) throws Exception {
    if (Util.isInternetConnectionAvailable(false)){
        try {
            URL url = new URL(Constants.API_URL + "user/register");
            URLConnection urlConnection = url.openConnection();
            if (urlConnection instanceof HttpsURLConnection){
                HttpsURLConnection httpsURLConnection = (HttpsURLConnection) urlConnection;
                httpsURLConnection.setConnectTimeout(Constants.TIMEOUT);
                String params = String.format("first_name=%s&last_name=%s&school=%s&grade=%s&phone_number=%s&email=%s&username=%s&password=%s&password_confirmation=%s&portal=mobile&agreed_to_terms_and_services=%s",
                        URLEncoder.encode(firstName, "UTF-8"),
                        URLEncoder.encode(lastName, "UTF-8"),
                        URLEncoder.encode(school, "UTF-8"),
                        URLEncoder.encode(String.valueOf(grade.getId()), "UTF-8"),
                        URLEncoder.encode(phoneNumber, "UTF-8"),
                        URLEncoder.encode(email, "UTF-8"),
                        URLEncoder.encode(username, "UTF-8"),
                        URLEncoder.encode(password, "UTF-8" ),
                        URLEncoder.encode(password, "UTF-8" ),
                        URLEncoder.encode("on", "UTF-8" ));
                httpsURLConnection.setDoOutput(true);
                httpsURLConnection.setRequestMethod("POST");
                OutputStreamWriter wr = new OutputStreamWriter(httpsURLConnection.getOutputStream());
                wr.write(params);
                wr.flush();
                InputStream inputStream = httpsURLConnection.getInputStream();
                BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
                byte[] data = new byte[1024];
                StringBuilder stringBuilder = new StringBuilder();
                int readCount;
                while ((readCount = bufferedInputStream.read(data)) > 0) {
                    String bufferString = new String(Arrays.copyOf(data, readCount));
                    stringBuilder.append(bufferString);
                    Arrays.fill(data, (byte) 0);
                }
                String response = stringBuilder.toString();
                JSONObject jsonObject = new JSONObject(response);
                boolean success = jsonObject.getBoolean("success");
                if (success) {
                    JSONObject userJSONObject = jsonObject.getJSONObject("user");
                    this.firstName = userJSONObject.getString("first_name");
                    this.lastName = userJSONObject.getString("last_name");
                    this.school = userJSONObject.getString("school");
                    this.grade = Grade.getGrade(userJSONObject.getInt("grade_id"));
                    this.email = userJSONObject.getString("email");
                    this.phoneNumber = userJSONObject.getString("phone_number");
                    this.username = userJSONObject.getString("username");
                    this.accountStatus = User.getAccountStatusFromString(jsonObject.getString("account_status"));
                    this.setId(userJSONObject.getInt("id"));
                    this.save(context);
                }
                else {
                    throw new Exception(jsonObject.getJSONObject("errors").toString());
                }
            }
        }
        catch (IOException e){
            throw new Exception("Could not connect to the internet.");
        } catch (JSONException e) {
            throw new Exception("There was an error in the connection..");
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }
    }
    else {
        throw new Exception("Could not connect to the internet");
    }
}


我当前的代码

    public void register(Context context) throws Exception {

    if (Util.isInternetConnectionAvailable(false)) {

        try {
            String url = Constants.API_URL + "user/register";
            OkHttpClient client = new OkHttpClient();
            Response response;
            Request request;

            RequestBody requestBody = new FormBody.Builder()
                    .add("first_name", URLEncoder.encode(firstName, "UTF-8"))
                    .add("last_name", URLEncoder.encode(lastName, "UTF-8"))
                    .add("school", URLEncoder.encode(school, "UTF-8"))
                    .add("grade", URLEncoder.encode(String.valueOf(grade.getId()), "UTF-8"))
                    .add("phone_number", URLEncoder.encode(phoneNumber, "UTF-8"))
                    .add("email", URLEncoder.encode(email, "UTF-8"))
                    .add("username", URLEncoder.encode(username, "UTF-8"))
                    .add("password", URLEncoder.encode(password, "UTF-8"))
                    .add("password_confirmation", URLEncoder.encode(password, "UTF-8"))
                    .add("portal", "mobile")
                    .add("agreed_to_terms_and_services", URLEncoder.encode("on", "UTF-8"))
                    .build();

            request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();

            response = client.newCall(request).execute();

            JSONObject jsonObject = new JSONObject(response.body().string().trim());

            boolean success = jsonObject.getBoolean("success");
            if (success) {
                JSONObject userJSONObject = jsonObject.getJSONObject("user");
                this.firstName = userJSONObject.getString("first_name");
                this.lastName = userJSONObject.getString("last_name");
                this.school = userJSONObject.getString("school");
                this.grade = Grade.getGrade(userJSONObject.getInt("grade_id"));
                this.email = userJSONObject.getString("email");
                this.phoneNumber = userJSONObject.getString("phone_number");
                this.username = userJSONObject.getString("username");
                this.accountStatus = User.getAccountStatusFromString(jsonObject.getString("account_status"));
                this.setId(userJSONObject.getInt("id"));
                this.save(context);
            } else {
                throw new Exception(jsonObject.getJSONObject("errors").toString());
            }
        } catch (IOException e) {
            throw new Exception("Could not connect to the internet.");
        } catch (JSONException e) {
            throw new Exception("There was an error in the connection..");
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }
    } else {
        throw new Exception("Could not connect to the internet");
    }
}

1 个答案:

答案 0 :(得分:1)

在某些php框架中,Sessions存储为cookie。所以你需要做的是使用CookieManager。查看以下question的第一个答案中的第二个选项: 并且还使用:

addEncoded("first_name", URLEncoder.encode(firstName, "UTF-8"))
方法 而不是

add("first_name", URLEncoder.encode(firstName, "UTF-8"))
因为您使用的是编码值。