Java HttpURLConnection вызывает удаленный сервер и возвращает 500 статус - PullRequest
0 голосов
/ 23 октября 2018

Я хочу вызвать удаленный сервер, используя HttpURLConnection, вот моя функция:

public String invokeAwvsServer(String api, String param, String method){
    System.out.println(api+param);
    BufferedReader reader = null;
    HttpURLConnection connection = null;
    OutputStreamWriter out = null;
    try {
        URL url = new URL(api);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestMethod(method); 
        connection.setRequestProperty("Content-Type", "application/json"); 
        connection.setRequestProperty("X-Auth", apiKey);
        connection.connect();

        if(method.equalsIgnoreCase("POST")){
            out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); 
            out.append(param);
            out.flush();
        }
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        String line;
        StringBuffer res = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            res.append(line);
        }
        return res.toString();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(reader != null){
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(connection != null){
            connection.disconnect();
        }
        if(out != null){
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return "error"; 

}

Я использую эту функцию в своем собственном классе и работает хорошо, но если я вызываю ее в другом классе, удаленный сервервернуть код состояния 500 и JVM выдает исключение вроде:

java.io.IOException: Server returned HTTP response code: 500 for URL:...

В чем причина? Большое спасибо :)

...