繁体   English   中英

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

[英]How to keep connection alive or maintain a session in OkHttp

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

https://mywebsite/api/user/register/start
然后第二次请求带有表单参数的url

  HTTPS:// mywebsite / API /用户/寄存器 
以防万一有人想看到我以前和当前的代码:
我以前的代码

  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"); } } 

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

addEncoded("first_name", URLEncoder.encode(firstName, "UTF-8"))
方法代替

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM