如何使用 android 中的 HttpUrlConnection 向服务器发送更新请求,例如 'GET' 和 'POST' 方法

How to send Update request to server using HttpUrlConnection in android like 'GET' and 'POST' methods

我正在使用 HttpUrlConnection 从 android 设备发送 API 请求,如下所示

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

和Post方法就像

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();

}

方法调用完成如下编码

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

并且调用 get 方法看起来像

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

Get 和 Post 方法都运行良好,但我正在讨论如何将更新请求发送到服务器,类似于 GET 和 POST 请求

我从下面的 link 得到了解决方案,我需要做的就是用 "PUT" 替换 "POST" 并且 url 应该看起来像' http://urladdress/myamailId' 和数组格式的值

Send Put request

我需要做的是在我的代码中添加以下方法

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

我的调用方法应该是这样的

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