0

I'm writing an application in which both the server-side and client codes are written by me, I'm not using any frameworks (e.g Spring Boot etc). when I send an http GET request from my android device to my laptop (which runs the server code), the request method that I had already explicitly set using setRequestMethod("GET") becomes post, I also checked it using wireshark and it also shows that the request is a POST not a get.

The code for sending the requests from android device:

public class ClientHttpUtils {
    private final static Gson GSON = GsonUtils.getInstance();
    private static final ExecutorService executorService = Executors.newFixedThreadPool(4);

public static <T> void get(
            String path,
            Map<String, String> query,
            Class<T> contentType,
            RequestErrorCallback onError,
            RequestSuccessCallback<T> onSuccess
    ) {
       execute("GET", path, null, query, null, contentType, onError, onSuccess);
    }

private static <T> void execute(
            String method,
            String path,
            Serializable data,
            Map<String, String> query,
            Headers headers,
            Class<T> contentType,
            RequestErrorCallback onError,
            RequestSuccessCallback<T> onSuccess
    ) {
        executorService.submit(()-> {
            try {
                ResponseModel<T> responseModel = executeRequest(method, path, data, query, headers, contentType);
                if (responseModel != null) {
                    onSuccess.onRequestSuccess(responseModel);

                } else {
                    onError.onRequestError(new Exception("Request failed"));
                }

            } catch (Exception e) {
                onError.onRequestError(e);
            }
        });
    }

private static <T> ResponseModel<T> executeRequest(
            String method,
            String path,
            Serializable data,
            Map<String, String> query,
            Headers headers,
            Class<T> contentType
    ) throws IOException {

        ResponseModel<T> responseModel = null;

        URL url = new URL(API.BASE_URL + path + mapToQuery(query));

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(method);
        conn.setDoOutput(true);

        if(headers != null) {
            for (String header: headers.keySet()){
                conn.setRequestProperty(header, String.join(",", headers.get(header)));
            }
        }

        if (data != null && method.equals("POST")) {
            byte[] bytes = SerializationUtils.serialize(data);
            conn.setRequestProperty("Content-Type", "application/octet-stream");
            conn.setRequestProperty("Content-Length", String.valueOf(bytes.length));
            conn.getOutputStream().write(bytes);
        } else {
            conn.setRequestProperty("Content-Type", "application/json");
        }

        if(conn.getResponseCode() == StatusCode.SUCCESS){
            responseModel = GSON.fromJson(
                    new InputStreamReader(conn.getInputStream()),
                    TypeToken.getParameterized(ResponseModel.class, contentType).getType());
        }
        else {
            responseModel = GSON.fromJson(
                    new InputStreamReader(conn.getErrorStream()),
                    TypeToken.getParameterized(ResponseModel.class, contentType).getType());
        }

        return responseModel;
    }
    private static String mapToQuery(Map<String, String> query) {
        StringBuilder queryStr = new StringBuilder();

        if (query != null) {
            queryStr = new StringBuilder("?");
            for (Map.Entry<String, String> entry : query.entrySet()) {
                String entity = entry.getValue();
                try {
                    entity = URLEncoder.encode(entity, StandardCharsets.UTF_8.toString());
                } catch (Exception ignore) {
                }

                queryStr.append(entry.getKey()).append("=").append(entity).append("&");
            }
            queryStr = new StringBuilder(queryStr.substring(0, queryStr.length() - 1));
        }

        return queryStr.toString();
    }
}

the ResponseModel<T> class:

public class ResponseModel<T> {

    private final int status;
    private final boolean success;
    private final String message;
    private final T content;

    public ResponseModel(int status, boolean success, String message, T content) {
        this.status = status;
        this.success = success;
        this.message = message;
        this.content = content;
    }

    public boolean isSuccess() {
        return success;
    }
    public int getStatus() {
        return status;
    }

    public String getMessage() {
        return message;
    }

    public T get() {
        return content;
    }
}

also this is the code that creates my server: httpServer = HttpServer.create(new InetSocketAddress("192.168.1.X",API.PORT), 0); and the endpoint for performing sign-in is /auth/sign-in/. if needed i can post a captured request using wireshark too. if any change is needed in the format of my question or anything I would do it quickly just say it in comments. thanks everyone in advance.

I have already read this post on SO but adding a slash to my request URI (e.g converting /auth/sign-in?username=something... to /auth/sign-in/?username=something...) niether adding one to the end of my request could fix my problem. on my server side code i have a HttpServer object and I couldn't find anything like allowNullPathInfo() as said in the SO post I shared. here are my codes for sending and handling the requests.

  • Base don the code you have posted you should build a minimal Java program that demonstrate your problem and that can be directly executed. – Robert Jun 22 '23 at 13:30
  • 1
    Consider not using `setDoOutput(true)`: https://stackoverflow.com/questions/8587913/what-exactly-does-urlconnection-setdooutput-affect. – Computable Jun 22 '23 at 13:50
  • @5f3bde39-70a2-4df1-afa2-47f61b thanks a lot!!! that fixed my issue. consider posting your comment as the answer. – Farbod Bijary Jun 22 '23 at 13:57

0 Answers0