2012-05-24 2 views
3

Appache HTTP Components 라이브러리는 일반 웹 사이트와 통신하는 데는 문제가 없지만 웹 서비스에는 연결할 수 없습니다.아파치 HttpClient로 웹 서비스에 연결

Jersey 프레임 워크를 사용하여 Web Service-REST와 통신 할 Java Desktop 응용 프로그램 내에서 실행되는 구성 요소를 빌드 중입니다. 웹 서비스가 실행 중이고 웹 브라우저 및 netbeans의 Test-Web-Service 기능과 통신 할 수 있습니다.

일반 웹 페이지 또는 내 컴퓨터에서 실행중인 Glassfish 웹 서버의 기본 페이지에서 읽으려고하면 클라이언트 코드가 제대로 작동합니다. 클라이언트 프로그램 (아래 코드)을 사용하여 웹 서비스에 접속하려고하면 웹 서버에서 404 찾을 수 없음 오류가 발생합니다.

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); 
    } 
    } 
} 

온라인 또는 로컬 호스트가 아닌 웹 서비스 사이트 일반 웹 사이트로 이동, 출력은 웹 페이지의 내용으로 이어

HTTP/1.1 200 OK 

입니다.

위의 코드는 나에게

HTTP/1.1 404 Not Found 


편집을 제공합니다 다음은 웹 서비스에 대한 코드입니다. 웹 서비스 코드는 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; 
    } 

} 
+0

당신이'HTTP를 입력 할 때 발생합니다 // localhost : 8080/Proctorest/resources/helloWorld'를 웹 브라우저에서 사용하거나 'curl'/'wget'을 사용 하시겠습니까? –

+0

helloWorld 리소스는 @get 메서드를 구현하므로 웹 브라우저에서 예상 한 페이지를 제공합니다. 정말 질문입니다. Glassfish가 웹 브라우저 요청에 응답하지만 Java 클라이언트 요청에 응답하지 않는 이유는 무엇입니까? – Thorn

답변

3

난 당신이 서비스를 배포하는 방법을 볼 수 없습니다.

시도 변화

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

것은이 "Helloworld"

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

또는 시도를 소문자로 (낙타의 경우는 서비스에 대한 이례적인 일이다) ROUTE

을 얻는 방법을

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

U : ... \ HelloWorld1에 \ HelloWorld1에 웹 \ 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) // 로컬 호스트 : 8080/HW<context-root>/HW</context-root>

에서 U : ... \ HelloWorld1에 \ HelloWorld1에 웹 \ 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.자바

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

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

C) // localhost를하십시오 8080/HW/HW/helloworld를

@Path("/helloworld")에서 풋) b)는 함께 귀하의 3 개 파일에서 C) 부분.

주의 사항 : 넷빈즈가 표시 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));  
    } 
.... 

OUTPUT

debug: 
HTTP/1.1 200 OK 

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

Netbeans에서 GlassFish로 서비스를 배포하고 있습니다. 이것은 새로운 프로젝트 마법사에서 만들 수있는 데모 응용 프로그램이며 여기에 몇 가지 추가 리소스가 추가되었지만 위 코드에서 데모와 함께 제공되는 리소스를 테스트하고 있습니다. URI의 철자는 문제가 아닙니다. @resource 주석의 철자와 대소 문자를 검사했는데 웹 브라우저가 URI에 제대로 접근 할 수 있습니다. – Thorn

+0

배포 코드를 알려주십시오. –

+0

이 작업에 시간을내어 주셔서 감사합니다. – Thorn