Slow response to api using HttpURLConnection

1

I'm having a critical problem, when I send a request to the API, it always takes a long time to receive the response, I'm using gcm too, it always arrives the moment the request is sent.

But when the function goes in the API, it is already delayed, it has already taken more than 2 minutes.

The worst is that sometimes it comes fast and in other cases not, the problem is not on the internet, so I noticed it is also not on the server, since the restfull client returns the result fast. The function I'm using on Android is this.

public static String postHttp(String targetURL, String urlParameters)
{
    URL url;
    HttpURLConnection connection = null;
    try {
        //Create connection
        url = new URL(targetURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");

        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Content-Language", "en-US");

        connection.setUseCaches(false);
        connection.setDoInput(true);


        //Send request
        OutputStreamWriter w = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        w.write(urlParameters);
        w.flush();
        w.close ();

        //Get Response
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();
        return sb.toString();

    } catch (Exception e) {
        String erro = "Erro de conexao com servidor (Método POST) - " + e.getMessage();
       // UpMotoLog.reportException(erro);
        Log.d("Exception", e.getMessage());
        return null;

    } finally {

        if(connection != null) {
            connection.disconnect();
        }
    }
}
    
asked by anonymous 11.08.2016 / 22:30

0 answers