I ran into the problem of «URL works in browser, but when I do http-get in java I get a 500 Error».
In my case the problem was that the regular http-get ended up in an infinite redirect loop between /default.aspx and /login.aspx
URL oUrl = new URL(url);
HttpURLConnection con = (HttpURLConnection) oUrl.openConnection();
con.setRequestMethod("GET");
...
int responseCode = con.getResponseCode();
What was happening was: The server serves up a three-part cookie and con.getResponseCode() only used one of the parts. The cookie data in the header looked like this:
header.key = null
value = HTTP/1.1 302 Found
...
header.key = Location
value = /default.aspx
header.key = Set-Cookie
value = WebCom-lbal=qxmgueUmKZvx8zjxPftC/bHT/g/rUrJXyOoX3YKnYJxEHwILnR13ojZmkkocFI7ZzU0aX9pVtJ93yNg=; path=/
value = USE_RESPONSIVE_GUI=1; expires=Wed, 17-Apr-2115 18:22:11 GMT; path=/
value = ASP.NET_SessionId=bf0bxkfawdwfr10ipmvviq3d; path=/; HttpOnly
...
So the server when receiving only a third of the needed data got confused: You’re logged in! No wait, you have to login. No, you’re logged in, …
To work around the infinite redirect-loop I had to manually look for re-directs and manually parse through the header for «Set-cookie» entries.
con = (HttpURLConnection) oUrl.openConnection();
con.setRequestMethod("GET");
...
log.debug("Disable auto-redirect. We have to look at each redirect manually");
con.setInstanceFollowRedirects(false);
....
int responseCode = con.getResponseCode();
With this code the parsing of the cookie, if we get a redirect in the responseCode:
private String getNewCookiesIfAny(String origCookies, HttpURLConnection con) {
String result = null;
String key;
Set<Map.Entry<String, List<String>>> allHeaders = con.getHeaderFields().entrySet();
for (Map.Entry<String, List<String>> header : allHeaders) {
key = header.getKey();
if (key != null && key.equalsIgnoreCase(HttpHeaders.SET_COOKIE)) {
// get the cookie if need, for login
List<String> values = header.getValue();
for (String value : values) {
if (result == null || result.isEmpty()) {
result = value;
} else {
result = result + "; " + value;
}
}
}
}
if (result == null) {
log.debug("Reuse the original cookie");
result = origCookies;
}
return result;
}
I have started a small project in Java.
I have to create a client which will send xml to a url as a HTTP POST request.
I try it using java.net.*
package (Following is the piece of code) but I am getting error as follows:
java.io.IOException: Server returned HTTP response code: 500 for URL: "target url"
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
at newExample.main(newExample.java:36)
My code is as follows:
try {
URL url = new URL("target url");
URLConnection connection = url.openConnection();
if( connection instanceof HttpURLConnection )
((HttpURLConnection)connection).setRequestMethod("POST");
connection.setRequestProperty("Content-Length", Integer.toString(requestXml.length()) );
connection.setRequestProperty("Content-Type","text/xml; charset:ISO-8859-1;");
connection.setDoOutput(true);
connection.connect();
// Create a writer to the url
PrintWriter writer = new PrintWriter(new
OutputStreamWriter(connection.getOutputStream()));
// Get a reader from the url
BufferedReader reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
writer.println();
writer.println(requestXml);
writer.println();
writer.flush();
String line = reader.readLine();
while( line != null ) {
System.out.println( line );
line = reader.readLine();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Please help with suitable examples or any other ways of doing this.
Point errors/mistakes in above code or other possibilities.
My Web Service is in spring framework
xml to send is in the string format: requestXml
asked Mar 1, 2011 at 8:08
sushilsushil
811 gold badge1 silver badge3 bronze badges
3
The problem lies in below code
// Get a reader from the url
BufferedReader reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
As the service might not always return you the proper response… as you are calling a service through http, it can be possible that the server itself is not available or the service is not available. So you should always check for the response code before reading response from streams, based on the response code you’ve to decide whether to read it from inputStream for success response or from errorStream for failure or exception condition.
BufferedReader reader = null;
if(connection.getResponseCode() == 200)
{
reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
}
else
{
reader = new BufferedReader(new
InputStreamReader(connection.getErrorStream()));
}
This would resolve the problem
answered Oct 21, 2012 at 20:38
2
The problem is inside your server code or the server configuration:
10.5.1 500 Internal Server Error
The server encountered an unexpected condition which prevented it from fulfilling the request.
(w3c.org/Protocols)
If the server is under your control (should be, if I look at the URL [before the edit]), then have a look at the server logs.
answered Mar 1, 2011 at 8:14
Andreas DolkAndreas Dolk
113k18 gold badges179 silver badges267 bronze badges
Well, you should close your streams and connections. Automatic resource maangement from Java 7 or http://projectlombok.org/ can help. However, this is probably not the main problem.
The main problem is that the server-side fails. HTTP code 500 means server-side error. I can’t tell you the reason, because I don’t know the server side part. Maybe you should look at the log of the server.
answered Mar 1, 2011 at 8:14
v6akv6ak
1,6262 gold badges12 silver badges27 bronze badges
I think that your problem is that you are opening the input stream before you have written and closed the output stream. Certainly, the Sun Tutorial does it that way.
If you open the input stream too soon, it is possible that the output stream will be closed automatically, causing the server to see an empty POST request. This could be sufficient to cause it to get confused and send a 500 response.
Even if this is not what is causing the 500 errors, it is a good idea to do things in the order set out in the tutorial. For a start, if you accidentally read the response before you’ve finished writing the request, you are likely to (at least temporarily) lock up the connection. (In fact, it looks like your code is doing this because you are not closing the writer before reading from the reader.)
A separate issue is that your code does not close the connection in all circumstances, and is therefore liable to leak network connections. If it does this repeatedly, it is likely to lead to more IOExceptions.
answered Mar 1, 2011 at 9:33
Stephen CStephen C
694k94 gold badges798 silver badges1210 bronze badges
If you are calling an External Webservice and passing a JSON in the REST call, check the datatype of the values passed.
Example:
{ "originalReference":"8535064088443985",
"modificationAmount":
{ "amount":"16.0",
"currency":"AUD"
},
"reference":"20170928113425183949",
"merchantAccount":"MOM1"
}
In this example, the value of amount was sent as a string and the webservice call failed with Server returned HTTP response code: 500.
But when the amount: 16.0 was sent, i.e an Integer was passed, the call went through. Though you have referred API documentation while calling such external APIs, small details like this could be missed.
kalabalik
3,7922 gold badges21 silver badges49 bronze badges
answered Sep 29, 2017 at 11:31
Добрый день.
Возможно исправить ошибку просто, но я новичок, так что не судите строго)
Если нужно будет дополнительная информация по коду или там конфигурации,
пишите я скину в комментарии.
ошибку я конечно же пытался решить сам, много прогуглил, но пока сообразить как
исправить не смог…
— «при запуске сервера начальная страница открывается нормально, однако когда
я хочу перейти по адресу возникает подобное исключение:»
HTTP Status 500 – Internal Server Error
Type Exception Report
Message Servlet.init() for servlet [dispatcher] threw exception
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
javax.servlet.ServletException: Servlet.init() for servlet [dispatcher] threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:543)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:698)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:367)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:639)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:882)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1647)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.base/java.lang.Thread.run(Thread.java:829)
Root Cause
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accountController' defined in file [C:codingByBrutalItJdbcCrudApplicationtargetJdbcCrudApplicationWEB-INFclassescomexamplecontrollerAccountController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.dao.AccountDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800)
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:229)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1372)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1222)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:702)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:578)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:530)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:170)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:543)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:698)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:367)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:639)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:882)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1647)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.base/java.lang.Thread.run(Thread.java:829)
Root Cause
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.dao.AccountDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1790)
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1346)
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300)
org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887)
org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791)
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:229)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1372)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1222)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:702)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:578)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:530)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:170)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:543)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:698)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:367)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:639)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:882)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1647)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.base/java.lang.Thread.run(Thread.java:829)
Note The full stack trace of the root cause is available in the server logs.
Apache Tomcat/8.5.78
Пользователи интернета и владельцы сайтов периодически сталкиваются с различными ошибками на веб-страницах. Одной из самых распространенных ошибок является error 500 (ошибка 500). Поговорим в нашей статье о том, что это за ошибка и как ее исправить.
Где и когда можно встретить ошибку 500
Вы можете увидеть ошибку на любом веб-ресурсе, браузере и устройстве. Она не связана с отсутствием интернет-соединения, устаревшей версией операционной системы или браузера. Кроме того, эта ошибка не указывает на то, что сайта не существует или он больше не работает.
Ошибка 500 говорит о том, что сервер не может обработать запрос к сайту, на странице которого вы находитесь. При этом браузер не может точно сообщить, что именно пошло не так.
Отображаться ошибка может по-разному. Вот пример:
Если вы решили купить что-то в любимом интернет-магазине, но увидели на сайте ошибку 500, не стоит сильно огорчаться – она лишь сообщает о том, что вам нужно подождать, пока она будет исправлена.
Если ошибка появилась на вашем сайте, то нужно скорее ее исправлять. Далее я расскажу, как это можно сделать.
Комьюнити теперь в Телеграм
Подпишитесь и будьте в курсе последних IT-новостей
Подписаться
Причины возникновения ошибки
Итак, ошибка 500 возникает, когда серверу не удается обработать запрос к сайту. Из-за этого пользователи не могут попасть на сайт, а поисковые системы полноценно с ним работать. Очевидно, что ошибка нуждается в исправлении. В первую очередь необходимо найти проблему.
Основной причиной ошибки 500 может быть:
- Неверный синтаксис файла .htaccess. htaccess – это файл, в котором можно задавать настройки для работы с веб-сервером Apache и вносить изменения в работу сайта (управлять различными перенаправлениями, правами доступа к файлам, опциями PHP, задавать собственные страницы ошибок и т.д.).
Узнать больше о файле .htaccess можно в статье «Создание и настройка .htaccess». - Ошибки в скриптах сайта, то есть сценариях, созданных для автоматического выполнения задач или для расширения функционала сайта.
- Нехватка оперативной памяти при выполнении скрипта.
- Ошибки в коде CMS, системы управления содержимым сайта. В 80% случаев виноваты конфликтующие плагины.
Год хостинга в подарок при заказе лицензии 1С-Битрикс
Выбирайте надежную CMS с регулярными обновлениями системы и профессиональной поддержкой.
Заказать
Как получить больше данных о причине ошибки
Что означает ошибка 500, мы теперь знаем. Когда она перестала быть таким загадочным персонажем, не страшно копнуть глубже — научиться определять причину ошибки. В некоторых случаях это можно сделать самостоятельно, так что обращаться за помощью к профильному специалисту не понадобится.
Отображение ошибки бывает разным. Ее внешний облик зависит от того, чем она вызвана.
Самые частые причины ошибки 500 можно распознать по тексту ошибки или внешнему виду страницы.
- Сообщение Internal Server Error говорит о том, что есть проблемы с файлом .htaccess (например, виновата некорректная настройка файла). Убедиться, что .htaccess является корнем проблемы, поможет следующий прием: переименуйте файл .htaccess, добавив единицу в конце названия. Это можно сделать с помощью FTP-клиента (например, FileZilla) или файлового менеджера на вашем хостинге (в Timeweb такой есть, с ним довольно удобно работать). После изменения проверьте доступность сайта. Если ошибка больше не наблюдается, вы нашли причину.
- Сообщение HTTP ERROR 500 или пустая страница говорит о проблемах со скриптами сайта. В случае с пустой страницей стоит учесть, что отсутствие содержимого сайта не всегда указывает на внутреннюю ошибку сервера 500.
Давайте узнаем, что скрывается за пустой страницей, обратившись к инструментам разработчика. Эта браузерная панель позволяет получить информацию об ошибках и другие данные (время загрузки страницы, html-элементы и т.д.).
Как открыть панель разработчика
- Нажмите клавишу F12 (способ актуален для большинства браузеров на Windows). Используйте сочетание клавиш Cmd+Opt+J, если используете Google Chrome на macOS. Или примените комбинацию Cmd+Opt+C в случае Safari на macOS (но перед этим включите «Меню разработки» в разделе «Настройки» -> «Продвинутые»). Открыть инструменты разработчика также можно, если кликнуть правой кнопкой мыши в любом месте веб-страницы и выбрать «Просмотреть код» в контекстном меню.
- Откройте вкладку «Сеть» (или «Network») и взгляните на число в поле «Статус». Код ответа об ошибке 500 — это соответствующая цифра.
Более детальную диагностику можно провести с помощью логов.
Простыми словами: лог — это журнал, в который записывается информация об ошибках, запросах к серверу, подключениях к серверу, действиях с файлами и т.д.
Как вы видите, данных в логи записывается немало, поэтому они разделены по типам. За сведениями о нашей ошибке можно обратиться к логам ошибок (error_log). Обычно такие логи предоставляет служба поддержки хостинга, на котором размещен сайт. В Timeweb вы можете включить ведение логов и заказать необходимые данные в панели управления. Разобраться в полученных логах поможет статья «Чтение логов».
Как устранить ошибку
Теперь поговорим о том, как исправить ошибку 500. Вернемся к популярным причинам этой проблемы и рассмотрим наиболее эффективные способы решения.
Ошибки в файле .htaccess
У этого файла довольно строгий синтаксис, поэтому неверно написанные директивы (команды) могут привести к ошибке. Попробуйте поочередно удалить команды, добавленные последними, и проверьте работу сайта.
Также найти проблемную директиву можно с помощью логов ошибок (через те же инструменты разработчика в браузере). На ошибку в директиве обычно указывает фраза «Invalid command». Информацию о верном написании директивы или способе исправления ошибок в .htaccess вы можете найти в интернете. Не нужно искать, почему сервер выдает ошибку 500, просто введите в строку поиска название нужной команды или текст ошибки из логов.
Ошибки в скриптах сайта
Скрипт не запускается
Обычно это происходит, когда существует ошибка в скрипте или функция, которая не выполняется. Для успешного запуска скрипта функция должна быть верно прописана, поддерживаться сервером и выполняться от используемой версии PHP. Бывают ситуации, когда функция несовместима с определенными версиями PHP. Получить более подробную информацию о той или иной функции можно в интернете.
Не хватает оперативной памяти
Если в логах вы видите ошибку «Allowed memory size», для устранения ошибки 500 стоит оптимизировать работу скрипта. Вы можете воспользоваться специальными расширениями для анализа производительности скрипта или обратиться за помощью к специалисту, который поработает над его оптимизацией.
Если ваш сайт размещен на отдельном физическом или виртуальном сервере, можно попробовать увеличить максимальное использование оперативной памяти на процесс (memory_limit). На шаред хостинге этот параметр обычно не изменяется, но есть возможность купить хостинг помощнее.
Ошибки в CMS
Если код CMS содержит неверный синтаксис, это может вывести сайт из строя. В таком случае логи сообщат вам об ошибке 500 текстом «PHP Parse error: syntax error, unexpected». Так происходит, когда некорректно работает плагин (или тема, используемая в CMS, но реже) либо есть ошибки в коде. Ошибка может быть допущена случайно, произойти при обновлении плагина или версии CMS.
При чтении логов обратите внимание на путь, который следует за сообщением об ошибке, ведь он может указать на проблемную часть кода или плагин. Если проблема в плагине, для восстановления работы сайта переименуйте на время папку, в которой он расположен. Попробуйте обновить плагин или откатить его до прежней версии. Если ситуацию не удается исправить, от расширения стоит отказаться либо заменить его аналогом.
Также в большинстве случаев подобные проблемы помогает решить поддержка CMS.
Информацию о других распространенных ошибках вы можете найти в статье «6 наиболее часто возникающих ошибок HTTP и способы их устранения».
Удачи!
The error 500: Java.lang.nullpointerexception is an error that is faced by some developers when executing their code. Moreover, end-users also encounter the error 500 when launching an application/game or accessing a particular website. Usually, the following type of error message is shown:
Due to the diversity of the coding world and tools used, it is not possible to cover those in this article but for a developer, the issue is either caused by an error in the code (like calling a function before its initializing) or a server-side error (like using doPost() when doGet() was required). If that is not the case, then reinstalling IDE (as discussed later) may clear the error for a developer.
For an end-user, if the issue is not on the server-side, then the following can be considered as the main factors leading to the error 500:
- Incompatible Browser: If a user is encountering the lang.nullpointerexception when accessing a particular website, then that browser’s incompatibility (like Edge) with that website may cause the error 500 as the website fails to call the function essential for its operations.
- Outdated Java Version on the System: If the system’s Java version is outdated, then its incompatibility with the game, application, or website might cause the error at hand as the Java modules of the system may fail to load.
- Interference from the System’s Firewall: If the system’s firewall is blocking the execution of Java (as a false positive), then the non-execution of the Java modules of the game, application, or website may lead to the error 500.
- Corrupt Installation of the Game or Java: If the game or Java’s installation is corrupt, then the essential game or Java modules may fail to operate and that may result in an error message.
Try Another Browser
If a particular website is failing to load in a browser with ‘Java.lang.nullpointerexception’, then that particular browser’s incompatibility with the website could be the root cause of the error 500 as the website may fail to perform a particular operation, which may be essential for the website’s functionality. Here, trying another browser may clear the error.
- Download and install another browser on your device/system (if already not present).
- Now launch the other browser (like Chrome or Firefox) and steer to the problematic website to check if it is operating fine.
- If not, check if clean booting of the system (especially, any Comcast-related applications) clears the error 500.
If the issue persists, check if the problematic website can be opened on another device (preferably, using another network).
Install Java on the System
Java is available for nearly every platform like smartphones. Windows PCs, Macs, Linux distros, etc. If the problematic application/game (like Minecraft) or website requires Java on a user’s system but is not installed on that system, then that can cause the error message as Java is not available for the execution of the related modules. Here, installing Java on the user’s system may solve the problem.
- Launch a web browser and head to the Java website to download Java.
- Now click on the Agree and Start Free Download.
Download Java - Then select the download as per the OS and system. Keep in mind if the problematic application, game, or website uses a particular version of Java, then make sure to download the required version.
- Afterward, wait till the Java download completes.
- Once downloaded, close all browser windows and any other running applications.
- Now right-click on the downloaded installer of Java and select Run as Administrator.
- Then follow the prompts on the screen to install Java and once done, restart your system.
- Upon restart, set up the Java installation as per the (if any) requirements of the problematic application, game, or website (like Environmental Variable, etc.).
- Now launch the problematic application, game, or website (in a browser) and check the issue is solved.
Update the System’s Java Version to the Latest Build
If the Java version on the system is outdated, it may cause incompatibility with the problematic website or application. Due to this incompatibility, certain Java-related modules may fail to execute properly and cause error 500. Here, updating the Java version of the system to the latest build may solve the problem.
- Press the Windows key and search for Java.
Open Configure Java - Then in the search results, open Configure Java and head to the Update tab.
Click Update Java in the Update Tab - Now click on the Update Now button and wait till the update process completes.
- Once done, restart your system and upon restart, check if the Java.Lang.NullPointerException issue is cleared.
Disable the System’s Firewall
You may encounter this error message if the system’s firewall is blocking the execution of certain Java modules as the blocked Java modules may fail to execute. In this case, disabling the system’s firewall may clear the error 500. For illustration, we will discuss the process of disabling ESET.
Warning:
Proceed at your own risk as disabling the system’s firewall may expose the system, network, and data to threats.
- Right-click on ESET in the hidden icons of the system’s tray and click on Pause Protection.
Pause ESET Protection and Firewall - Then click Yes (if a UAC prompt is shown) and afterward, select the time interval (like 1 hour) for which you want to disable the firewall.
- Now click on Apply and again, right-click on ESET.
- Then select Pause Firewall and afterward, confirm to disable ESET firewall.
- Now check if the system is clear of the error 500.
Reinstall IDE or Code Editor on the System
For a developer, if none of the code or server-side issues are causing the error message, then the corrupt installation of the IDE (like Adobe ColdFusion) or code editor could be the root cause of the issue.
Here, reinstalling the IDE or code editor may clear the error at hand. For illustration, we will discuss the process of reinstalling Adobe ColdFusion on a Windows PC. Before proceeding, make sure to back up essential code snippets or other data.
- Firstly, check if using the default skin or theme (like metallic) of the IDE or Code Editor (like SNAP editor) clears the error.
- If not, right-click Windows and open Apps & Features.
Open Apps & Features - Now expand the Adobe ColdFusion option and select Uninstall.
Uninstall Adobe ColdFusion - Then confirm to uninstall the Adobe ColdFusion and follow the prompts on the screen to uninstall it.
- Once done, restart your system and upon restart, right-click Windows.
- Now select Run and then delete the ColdFusion remnants from the following directories:
temp %temp% %ProgramData% Program Files Program Files (x86) appdata
Open the ProgramData Folder - Then reinstall Adobe ColdFusion and check if the error 500 is cleared.
Reinstall the Problematic Game
You may encounter the ‘error 500:Java.lang.nullpointerexception’ on a Java-based game (like Minecraft) if the game’s installation is corrupt as the game’s modules are not able to perform the designated role. In this scenario, reinstalling the problematic game may clear the error at hand. For elucidation, we will discuss the process of reinstalling Minecraft.
- Right-click Windows and open Run.
Open the Run Command Box from the Quick Access Menu - Now navigate to the following:
%appdata%
- Now open the .Minecraft folder and backup the Saves folder (to save the worlds you have been playing).
Copy the Saves Folder to the Minecraft - Then click Windows and search for Minecraft.
- Now right-click on it and select Uninstall.
Uninstall Minecraft - Then confirm to uninstall Minecraft and follow the prompts on the screen to uninstall the game.
- Once uninstalled, reboot your system and upon reboot, steer to the following path in Run:
%appdata%
- Then delete the .Minecraft folder and afterward, steer to the following path in Run:
AppData
Delete the Minecraft Folder in the Roaming Directory - Then delete all the Minecraft-related folders from all of the three following directories:
Local LocalLow Roaming
- Now reinstall Minecraft by using the official Minecraft installer and once reinstalled, check if the game is clear of the error 500.
Reinstall Java on the System
If the Java’s installation on your system itself is corrupt, then that can also be the cause of the issue as many of the Java libraries may not be available to the problematic game, application, or website. In this scenario, reinstalling Java on your system may clear the error 500. For illustration, we will discuss the process of reinstalling Java on a Windows system.
- Right-click Windows and open Apps & Features.
- Now expand the Java option and click on Uninstall.
Uninstall Java 64-bit Version - Then confirm to uninstall Java and follow the prompts on the screen to uninstall Java.
- Once uninstalled, restart your system, and upon restart, open the Run command box by pressing Windows + R keys.
- Now delete the Java remnants from the following paths:
C:Program FilesJava C:ProgramDataOracleJava C:Program Files (x86)Common FilesJava C:Program Files (x86)OracleJava ProgramData AppData temp %temp%
- Afterward, disable the system’s firewall (as discussed earlier) and reinstall the latest Java version (or the Java version required by the game, application, or website).
- Once reinstalled, restart your system and upon restart, hopefully, the system would be cleared of the error 500:Java.lang.nullpointerexception.
- If not, check if copying the msvcr71.dll file (from another working computer) to the following path clears the error (if the issue is occurring in a browser):
C:windowssystem32
If the issue persists and occurs with a particular website, application, or game, then you may contact support to check the backend for any server-side issues.
Kevin Arrows
Kevin Arrows is a highly experienced and knowledgeable technology specialist with over a decade of industry experience. He holds a Microsoft Certified Technology Specialist (MCTS) certification and has a deep passion for staying up-to-date on the latest tech developments. Kevin has written extensively on a wide range of tech-related topics, showcasing his expertise and knowledge in areas such as software development, cybersecurity, and cloud computing. His contributions to the tech field have been widely recognized and respected by his peers, and he is highly regarded for his ability to explain complex technical concepts in a clear and concise manner.