Java Rest 服务中的错误:连接被拒绝:连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20795104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:22:41  来源:igfitidea点击:

Error in Java Rest Service : Connection refused: connect

javarestenvironment-variables

提问by Parvathy

I am trying to create a rest service. But I got the following error after running.

我正在尝试创建休息服务。但是运行后出现以下错误。

Exception in thread "main" com.sun.jersey.api.client.ClientHandlerException: java.net.ConnectException: Connection refused: connect
    at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:151)
    at com.sun.jersey.api.client.Client.handle(Client.java:648)
    at com.sun.jersey.api.client.WebResource.handle(WebResource.java:680)
    at com.sun.jersey.api.client.WebResource.access0(WebResource.java:74)
    at com.sun.jersey.api.client.WebResource$Builder.get(WebResource.java:507)
    at astral.restservice.client.Test.main(Test.java:20)
Caused by: java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at sun.net.NetworkClient.doConnect(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.http.HttpClient.<init>(Unknown Source)
    at sun.net.www.http.HttpClient.New(Unknown Source)
    at sun.net.www.http.HttpClient.New(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at java.net.HttpURLConnection.getResponseCode(Unknown Source)
    at com.sun.jersey.client.urlconnection.URLConnectionClientHandler._invoke(URLConnectionClientHandler.java:249)
    at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:149)
    ... 5 more

Following is my web.xml :

以下是我的 web.xml :

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>astral.restservice</display-name>
  <servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>com.sun.jersey.config.property.packages</param-name>
      <param-value>astral.restservice</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>

Hello.java

你好.java

package astral.restservice;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

// Plain old Java Object it does not extend as class or implements 
// an interface

// The class registers its methods for the HTTP GET request using the @GET annotation. 
// Using the @Produces annotation, it defines that it can deliver several MIME types,
// text, XML and HTML. 

// The browser requests per default the HTML MIME type.

//Sets the path to base URL + /hello
@Path("/hello")
public class Hello {

  // This method is called if TEXT_PLAIN is request
  @GET
  @Produces(MediaType.TEXT_PLAIN)
  public String sayPlainTextHello() {
    return "Hello Jersey";
  }

  // This method is called if XML is request
  @GET
  @Produces(MediaType.TEXT_XML)
  public String sayXMLHello() {
    return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
  }

  // This method is called if HTML is request
  @GET
  @Produces(MediaType.TEXT_HTML)
  public String sayHtmlHello() {
    return "<html> " + "<title>" + "Hello Jersey" + "</title>"
        + "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";
  }

} 

Test.java

测试.java

package astral.restservice.client;

import java.net.URI;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
public class Test {
  public static void main(String[] args) {
    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client.resource(getBaseURI());
    // Fluent interfaces
    System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_PLAIN).get(ClientResponse.class).toString());
    // Get plain text
    System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_PLAIN).get(String.class));
    // Get XML
    System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_XML).get(String.class));
    // The HTML
    System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_HTML).get(String.class));


  }

  private static URI getBaseURI() {
    return UriBuilder.fromUri("http://localhost:8080/astral.restservice").build();
  }

} 

This is my project structure enter image description here

这是我的项目结构 在此处输入图片说明

Why I am getting this error? Thanks in advance.

为什么我收到这个错误?提前致谢。

I got the following error from browser after run it using tomcat v7

使用 tomcat v7 运行后,我从浏览器收到以下错误

HTTP Status 500 - Servlet.init() for servlet Jersey REST Service threw exception

type Exception report

message Servlet.init() for servlet Jersey REST Service threw exception

description The server encountered an internal error that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: Servlet.init() for servlet Jersey REST Service threw exception
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    java.lang.Thread.run(Unknown Source)

root cause

com.sun.jersey.spi.inject.Errors$ErrorMessagesException
    com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170)
    com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136)
    com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:199)
    com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:695)
    com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:690)
    com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:438)
    com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:287)
    com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:587)
    com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:213)
    com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:342)
    com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:516)
    javax.servlet.GenericServlet.init(GenericServlet.java:160)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    java.lang.Thread.run(Unknown Source)

note The full stack trace of the root cause is available in the Apache Tomcat/7.0.39 logs.
Apache Tomcat/7.0.39

I tried to run server using command prompt I got the following error, I set CATALINA_HOME,JAVA_HOME,CLASSPATH and add PATH also.

我尝试使用命令提示符运行服务器,但出现以下错误,我设置了 CATALINA_HOME、JAVA_HOME、CLASSPATH 并添加了 PATH。

**

**

D:\apache-tomcat-7.0.39\bin>startup
The CATALINA_HOME environment variable is not defined correctly
This environment variable is needed to run this program

D:\apache-tomcat-7.0.39\bin>startup.bat
The CATALINA_HOME environment variable is not defined correctly
This environment variable is needed to run this program

D:\apache-tomcat-7.0.39\bin>catalina.bat
The CATALINA_HOME environment variable is not defined correctly
This environment variable is needed to run this program

D:\apache-tomcat-7.0.39\bin>

**

**

采纳答案by kingAm

http://localhost:8080

simply access this link from your web browser. I think that your apache server is running on some other port. Please check the properties of server, and replace the port appropriately.

只需从您的网络浏览器访问此链接。我认为您的 apache 服务器正在其他端口上运行。请检查服务器的属性,并适当更换端口。

回答by JKK

In case anyone looks at this post, check to see how your calling the application

如果有人看到这篇文章,请检查您如何调用应用程序

I had:

我有:

java -jar test-suite.jar -dHost http://localhost:8080 -other params

I should have done this:

我应该这样做:

java -dHost http://localhost:8080 -other params -jar test-suite.jar

simple mistake, put your params first ahead of -jar

简单的错误,把你的参数放在 -jar 前面

回答by Balaji Boggaram Ramanarayan

Try to open port. You can do this by :

尝试打开端口。你可以这样做:

iptables -P INPUT ACCEPT

Note : The above commands opens up all ports

注意:以上命令打开所有端口