コード例 #1
0
  /**
   * This function will try login user in using hashmap as input. return result will be json web
   * token for that user.
   */
  public static String performLogin(HashMap<String, String> postDataParams) {
    String requestURL = "http://blooming-stream-2220.herokuapp.com/api/login";
    URL url;
    String response = "";
    try {
      url = new URL(requestURL);

      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setReadTimeout(15000);
      conn.setConnectTimeout(15000);
      conn.setRequestMethod("POST");
      conn.setDoInput(true);
      conn.setDoOutput(true);

      OutputStream os = conn.getOutputStream();
      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
      writer.write(HttpRequester.getPostDataString(postDataParams));
      writer.flush();
      writer.close();
      os.close();
      int responseCode = conn.getResponseCode();
      Log.d("tr.edu.code", responseCode + "");
      if (responseCode == HttpsURLConnection.HTTP_OK) {
        String line;
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = br.readLine()) != null) {
          response += line;
        }
      } else {
        response = "";
      }
    } catch (Exception e) {
      Log.d("tr.edu.code", e.getMessage());

      e.printStackTrace();
    }
    String token = "";

    try {
      JSONObject jsonObject = new JSONObject(response);
      token = jsonObject.getString("token");
    } catch (JSONException e) {
      Log.e("tr.edu", "Error parsing Json");
    }
    return token;
  }