java - 使用 apache HttpClient 连接到 Web 服务

标签 java rest

Appache HTTP Components库似乎可以很好地与常规网站通信,但无法连接到网络服务。

我正在构建要在 Java 桌面应用程序中运行的组件,该应用程序将使用 Jersey 框架与 Web 服务-REST 通信。 Web 服务正在运行,我可以将它与我的 Web 浏览器和 netbeans 中的 Test-Web-Service 功能进行通信。

如果我尝试从常规网页或什至是我机器上运行的 Glassfish Web 服务器的默认页面读取,客户端代码工作正常。 为什么当我尝试使用我的客户端程序(下面的代码)访问 Web 服务时,我会从 Web 服务器收到 404 Not Found 错误?

import java.io.*;
import org.apache.http.*;
import org.apache.http.client.*;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.client.methods.*;  //HttpHead, HttpPut, HttpGet, etc...
import org.apache.http.util.EntityUtils;

public class ApacheClientDemo {

  public static void demo() throws IOException {           
     String uri = "http://localhost:8080/Proctorest/resources/helloWorld";
     HttpClient httpclient = new DefaultHttpClient();
     HttpGet httpget = new HttpGet(uri);
     HttpResponse response = httpclient.execute(httpget);
     System.out.println(response.getStatusLine().toString());
     HttpEntity entity = response.getEntity();
     System.out.println();
     System.out.println(EntityUtils.toString(entity));       
  }

  public static void main(String[] args) {
    try {
        demo();
    }
    catch(IOException ioe) {
        System.out.println(ioe);
    }
  }
}

当转到在线的常规网站或本地托管的非 Web 服务站点时,输出为

 HTTP/1.1 200 OK

后面是网页内容。

上面的代码给了我

  HTTP/1.1 404 Not Found


编辑:下面是网络服务的代码。 Web 服务代码是从 Netbeans 示例项目生成的。 Netbeans Sample Web Service project

/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
*
* Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License.  When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
* 
* Contributor(s):
* 
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
* Microsystems, Inc. All Rights Reserved.
* 
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/

package helloworld;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;

/**
* REST Web Service
*
* @author mkuchtiak
*/

@Stateless
@Path("/helloWorld")
public class HelloWorldResource {

    @EJB
    private NameStorageBean nameStorage;
    /**
    * Retrieves representation of an instance of helloworld.HelloWorldResource
    * @return an instance of java.lang.String
    */
    @GET
    @Produces("text/html")
    public String getXml() {
        return "<html><body><h1>Hello "+nameStorage.getName()+"!</h1></body></html>";
    }

    /**
    * PUT method for updating an instance of HelloWorldResource
    * @param content representation for the resource
    * @return an HTTP response with content of the updated or created resource.
    */
    @PUT
    @Consumes("text/plain")
    public void putXml(String content) {
        nameStorage.setName(content);
    }
}

/////////// NameStorageBean .java

import javax.ejb.Singleton;

/** Singleton session bean used to store the name parameter for "/helloWorld" resource
*
* @author mkuchtiak
*/
@Singleton
public class NameStorageBean {

    // name field
    private String name = "World";

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

最佳答案

我看不到你是如何部署服务的。

尝试更改(驼峰式大小写对于服务来说不常见)

String uri = "http://localhost:8080/Proctorest/resources/helloWorld";

小写“helloworld”

String uri = "http://localhost:8080/Proctorest/resources/helloworld";

或者试试

String uri = "http://localhost:8080/helloworld";

如何获取路线

U:...\HelloWorld1\HelloWorld1\web\WEB-INF\sun-web.xml

<sun-web-app error-url="">
  <context-root>/HW</context-root>
  <class-loader delegate="true"/>
  <jsp-config>
    <property name="keepgenerated" value="true">
      <description>Keep a copy of the generated servlet class' java code.</description>
    </property>
  </jsp-config>
</sun-web-app>

a)//localhost:8080/HW 来自 <context-root>/HW</context-root>

U:...\HelloWorld1\HelloWorld1\web\WEB-INF\web.xml

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <servlet>
        <servlet-name>ServletAdaptor</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>ServletAdaptor</servlet-name>
        <url-pattern>/hw/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

b)//localhost:8080/HW/hw 来自 <url-pattern>/hw/*</url-pattern>

U:....\HelloWorld1\HelloWorld1\src\java\helloworld\HelloWorldResource.java

.....
/**
 * REST Web Service
 *
 * @author mkuchtiak
 */

@Stateless
@Path("/helloworld")
public class HelloWorldResource {
....

c)//localhost:8080/HW/hw/helloworld 来自 @Path("/helloworld")

将 3 个文件中的 a)b)c) 部分放在一起。

注意:Netbeans 显示的 url 是错误的,只有/HW 是正确的

...
    Incrementally deploying HelloWorld1
    Completed incremental distribution of HelloWorld1
    run-deploy:
    Browsing: http://localhost:8080/HW/resources/helloWorld
...

....
public static void demo() throws IOException {           
     String uri = "http://localhost:8080/HW/hw/helloworld";
     HttpClient httpclient = new DefaultHttpClient();
     HttpGet httpget = new HttpGet(uri);
     HttpResponse response = httpclient.execute(httpget);
     System.out.println(response.getStatusLine().toString());
     HttpEntity entity = response.getEntity();
     System.out.println();
     System.out.println(EntityUtils.toString(entity));       
  }
....

输出

debug:
HTTP/1.1 200 OK

<html><body><h1>Hello World!</h1></body></html>

关于java - 使用 apache HttpClient 连接到 Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10744053/

相关文章:

java - JTable 中的行计数器

java - Android 计算器给出错误答案

wcf - 用于 .NET 框架 3.5 的 WebApi HttpClient

java - Jersey 不遵循 302 重定向

rest - Firefox 附加 RESTclient - 如何输入 POST 参数?

java - REST 从 jQuery : Method Not Allowed error 中删除

Java:正则表达式仅匹配一个\n

java - 使用 guice 注入(inject)与 actor 抛出空指针

java - 在Java中获取最大值sql

rest - 如何将基本 HTTP 身份验证与 REST Web 服务 (Java+Jersey) 结合使用?