0

I am sending the API request from the android device with HttpUrlConnection like below

private static JSONObject get(Context ctx, String sUrl) {
    HttpURLConnection connection = null;
    String authUserName = "example";
    String authPassword = "exam123ple";

    String authentication = authUserName + ":" + authPassword;
    String encodedAuthentication = Base64
            .encodeToString(authentication.getBytes(), Base64.NO_WRAP);

    try {

        URL url = new URL(sUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Authorization",
                "Basic " + encodedAuthentication);
        connection.setRequestProperty("Accept-Charset", "utf-8,*");
        Log.d("Get-Request", url.toString());
        try {
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()));
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
            bufferedReader.close();
            Log.d("Get-Response", stringBuilder.toString());
            return new JSONObject(stringBuilder.toString());
        } finally {
            connection.disconnect();
        }
    } catch (Exception e) {
        Log.e("ERROR", e.getMessage(), e);
        return null;
    }
}

and Post method be like

private static JSONObject post(String sUrl, String body) {
    Log.d("post", sUrl);
    Log.d("post-body", sanitizeJSONBody(body));
    HttpURLConnection connection = null;

    String authentication = "hoffensoft" + ":" + "hoffen123soft";
    String encodedAuthentication = Base64
            .encodeToString(authentication.getBytes(), Base64.NO_WRAP);

    try {
        URL url = new URL(sUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Authorization",
                "Basic " + encodedAuthentication);
        connection.setRequestProperty("Accept-Charset", "utf-8,*");
        OutputStreamWriter streamWriter = new OutputStreamWriter(
                connection.getOutputStream());

        streamWriter.write(body);
        streamWriter.flush();
        StringBuilder stringBuilder = new StringBuilder();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStreamReader streamReader = new InputStreamReader(
                    connection.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(
                    streamReader);
            String response = null;
            while ((response = bufferedReader.readLine()) != null) {
                stringBuilder.append(response + "\n");
            }
            bufferedReader.close();

            Log.d("Post-Response",
                    sanitizeJSONBody(stringBuilder.toString()));
            return new JSONObject(stringBuilder.toString());
        } else {
            Log.d("Post-Error", connection.getResponseMessage());
            return null;
        }
    } catch (Exception exception) {
        Log.e("Post-Exception", exception.toString());
        return null;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

private static String buildSanitizedRequest(String url,
                                            Map<String, String> mapOfStrings) {

    Uri.Builder uriBuilder = new Uri.Builder();
    uriBuilder.encodedPath(url);
    if (mapOfStrings != null) {
        for (Map.Entry<String, String> entry : mapOfStrings.entrySet()) {
            Log.d("buildSanitizedRequest", "key: " + entry.getKey()
                    + " value: " + entry.getValue());
            uriBuilder.appendQueryParameter(entry.getKey(),
                    entry.getValue());
        }
    }
    String uriString;
    try {
        uriString = uriBuilder.build().toString(); // May throw an
        // UnsupportedOperationException
    } catch (Exception e) {
        Log.e("Exception", "Exception" + e);
    }

    return uriBuilder.build().toString();

}

The method calling has done like the below coding

public static JSONObject registerTask(Context ctx, String sUrl,
                                      String firstName, String lastName, String gender,
                                      String mobileNumber, String emailAddress, String password,
                                      String state, String city, String address, String userType,
                                      String pinCode, String loginInfo) throws JSONException, IOException {
    JSONObject request = new JSONObject();

    request.putOpt("firstName", firstName);
    request.putOpt("lastName", ((lastName == null) ? "" : lastName));
    request.putOpt("gender", gender);
    request.putOpt("email", emailAddress);
    request.putOpt("mobileNumber", mobileNumber);
    request.putOpt("password", password);
    request.putOpt("state", state);
    request.putOpt("city", city);
    request.putOpt("userType", userType);
    request.putOpt("address", address);
    request.putOpt("pinCode", pinCode);
    request.putOpt("loginTime", loginInfo);

    sUrl = sUrl + "userRegistration.php";
    return post(sUrl, request.toString());
}

And calling a get method looks like

public static JSONObject searchAvailability(Context ctx, String sUrl,
                                            String journeyDate, String returnDate, String vehicleType, String username) throws JSONException, IOException {
    Map<String, String> request = new HashMap<String, String>();
    request.put("journeyDate", journeyDate);
    request.put("returnDate", returnDate);
    request.put("vehicleType", vehicleType);
    request.put("username", username);

    sUrl = sUrl + "SearchAvailability.php";
    return get(ctx, buildSanitizedRequest(sUrl, request));
}

Both the Get and Post methods are working good but I am in dialoma about How to send update request to server as similar to GET and POST requests

Bethan
  • 971
  • 8
  • 23
  • Dude, just go for Retrofit2.0 or Volley, save yourself a lot of pain – TommySM Nov 16 '16 at 11:53
  • Your suggestion looks great but this is the existing project I just need to patch some code immediately as a quick solution, I am planning to move to Retrofit2.0 or Volley in my next app release as you said, thanks for your suggestion. – Bethan Nov 16 '16 at 11:55
  • @BKumar use post method for update – Damini Mehra Nov 16 '16 at 11:56
  • @DaminiMehra When I am trying to use post method for update API replying me the 'Method Not Allowed' response. – Bethan Nov 17 '16 at 07:10

1 Answers1

0

I got the solution from the below link, all I need to do is to replace the "POST" with "PUT" and the url should be look like 'http://urladdress/myamailId' and the values in array format

Send Put request

The thing I need to do is add the below method in my code

private static JSONObject put(String sUrl, String body) {
    Log.d("post", sUrl);
    Log.d("post-body", sanitizeJSONBody(body));
    HttpURLConnection connection = null;

    String authentication = "example" + ":" + "exam123ple";
    String encodedAuthentication = Base64
        .encodeToString(authentication.getBytes(), Base64.NO_WRAP);

    try {
        URL url = new URL(sUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("PUT");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Authorization",
            "Basic " + encodedAuthentication);
        connection.setRequestProperty("Accept-Charset", "utf-8,*");
        OutputStreamWriter streamWriter = new OutputStreamWriter(
            connection.getOutputStream());

        streamWriter.write(body);
        streamWriter.flush();
        StringBuilder stringBuilder = new StringBuilder();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStreamReader streamReader = new InputStreamReader(
                connection.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(
                streamReader);
            String response = null;
            while ((response = bufferedReader.readLine()) != null) {
                stringBuilder.append(response + "\n");
            }
            bufferedReader.close();

            Log.d("Post-Response",
                sanitizeJSONBody(stringBuilder.toString()));
            return new JSONObject(stringBuilder.toString());
        } else {
            Log.d("Post-Error", connection.getResponseMessage());
            return null;
        }
    } catch (Exception exception) {
        Log.e("Post-Exception", exception.toString());
        return null;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

and my calling method should look like

public static JSONObject registerTask(Context ctx, String sUrl,
                                  String firstName, String lastName, string username) throws JSONException, IOException {
    JSONObject request = new JSONObject();

    request.putOpt("firstName", firstName);
    request.putOpt("lastName", ((lastName == null) ? "" : lastName));

    sUrl = sUrl + "registration/"+username;
    return put(sUrl, request.toString());
}
Community
  • 1
  • 1
Bethan
  • 971
  • 8
  • 23