简体   繁体   中英

How to keep connection alive or maintain a session in OkHttp

I have a web service on a server and to register a user from the android app I first make a POST request to it to create the registration session and then make another POST request to it containing the form data. It worked fine using the built in HttpsURLConnection and now when I start using OkHttp; the server is treating each requests differently like they're coming from two different devices. How can I maintain the first connection I have and make another request to it? I have tried to make the requests with postman and it also works as expected. I first make an empty post call to such url:

https://mywebsite/api/user/register/start
and then second request to such a url with the form parameters

 https://mywebsite/api/user/register  
Just in case anyone wants to see my previous and current code:
My Previous Code

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


My Current Code

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

In some php frameworks, Sessions are stored as cookies. So what you need to do is use a CookieManager. Look at the second option in the first answer of the following question : and also use:

addEncoded("first_name", URLEncoder.encode(firstName, "UTF-8"))
method instead of

 add("first_name", URLEncoder.encode(firstName, "UTF-8")) 
since you are using encoded values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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