java - 使用 JAXRS 将 XML 编码为 Restful 服务的 JAVA 对象

标签 java xml rest jax-rs unmarshalling

我正在尝试根据用户上传的 XML 文件实现 boolean 返回(真/假)。例如,我有一个元素方向,指示它包含的数据类型。所以我有兴趣对数据进行整理并返回 boolean 值。

第 1 步:对 POST 方法感兴趣,并将使用 POSTMAN 进行测试Chrome 应用程序。

第 2 步:内容对象保存所有内容以进行编码和编码

包 validator .service;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

// Created the Contents object to hold everything for un marshaling and marshaling

@XmlRootElement( name = "contents" )
public class Contents
{
    @XmlElement
    String portalarea;

    @XmlElement
    String portalsubarea;

    @XmlElement
    String direction;

    public String getportalarea()
    {
        return portalarea;
    }

    public String getportalsubarea()
    {
        return portalsubarea;
    }

    public String getdirection()
    {
        return direction;
    }

}

第 3 步:使用验证类来接收请求并解码 XML 以返回 boolean 值。

package validatorService;

import java.io.InputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Unmarshaller;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

@Path ("/valid")
public class ValidatorService
{
    boolean n_value = false;
    boolean r_value = false;

    @POST
    @Produces( MediaType.TEXT_PLAIN )
    @Consumes( "application/xml" )
    public String validate( String xmlContent )
    {
        HttpClient httpclient = new DefaultHttpClient();

        try
        {
            if ( xmlContent != null )
            {
                if ( xmlContent.startsWith( "https" ) )
                {
                    HttpGet xmlGet = new HttpGet( xmlContent );

                    HttpResponse response = httpclient.execute( xmlGet );
                    int responseStatus = response.getStatusLine().getStatusCode();
                    // String responseMessage = response.getStatusLine().getReasonPhrase();

                    if ( responseStatus == 200 )
                    {
                        HttpEntity responseEntity = response.getEntity();
                        InputStream inStream = responseEntity.getContent();

                        Contents direction = unmarshalingContent( inStream, xmlContent );

                        if ( direction.equals( "N" ) )
                        {
                            n_value = true;


                        }
                        else if ( direction.equals( "R" ) )
                        {
                            r_value = true;


                    }
                    else
                    {
                        System.out.println( "Response Error : " + responseStatus ); // Should be
                                                                                    // handled
                                                                                    // properly
                    }

                }
                else
                {
                    System.out.println( " 'https' Format Error" ); // Should be handled properly
                }

                return "success";
            }

        }
        catch ( Exception e )
        {
            e.printStackTrace();
            System.out.println( " Error caught at catch " + e ); // Should be handled properly for
                                                                 // all exception
        }
        finally
        {
            httpclient.getConnectionManager().shutdown();
        }

        return null;
    }

    public Contents unmarshalingContent( InputStream inputStream, String resourceClass ) throws Exception
    {
        System.out.println( " welcome " );

        if ( resourceClass == "xmlContent" )
        {
            JAXBContext jc = JAXBContext.newInstance( "com.acme.bar" );
            Unmarshaller u = jc.createUnmarshaller();

            XMLInputFactory inputFactory = XMLInputFactory.newInstance();
            XMLStreamReader xReader = inputFactory.createXMLStreamReader( inputStream );

            JAXBElement<Contents> jaxBElement = (JAXBElement<Contents>) u.unmarshal( xReader, Contents.class );

            Contents portalArea = (Contents) jaxBElement.getValue();
            Contents portalSubarea = (Contents) jaxBElement.getValue();
            Contents direction = (Contents) jaxBElement.getValue();

            return direction;
        }
        throw new Exception( "Invalid resource request" );

    }
}

我是 RESTful 服务的新手,我阅读了一些文档,并根据说明尝试完成给定的任务。因此,非常感谢任何帮助、更正、指导、代码。

最佳答案

它可以简单得多。您不需要手动进行 XML 到 Java 对象的转换。 JAX-RS 提供商会自动执行此操作。

@POST
@Produces( MediaType.TEXT_PLAIN )
@Consumes( "application/xml" )
public Response validate(Contents con){ //con will be initialized by JAX-RS
  //validate your XML converted to object con
  boolean validation_ok = ...
  if(validation_ok){
     return Response.ok("true").build();
  }else{
     return Response.ok("false").build();
  }
}

关于java - 使用 JAXRS 将 XML 编码为 Restful 服务的 JAVA 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10538665/

相关文章:

java - 无法使用 @ContextConfiguration(classes={ ... }) 加载 ApplicationContext

java - 优化 Android/Java 代码 - 创建同一对象类型的多个实例

wcf - HTTP 错误 500.19 - 内部服务器错误 请求的页面无法 (WCF + REST + IIS7 + SSL)

java - 如何在 Spring 中从 JNDI 引用多个 bean?

javascript - HTTPServletResponse 方法 setStatus()

xml - XSLT 将 XML 同级移至子级

json - 为什么 RestTemplate 不将响应表示绑定(bind)到 PagedResources?

http - (Ab?)使用 http 自定义 header 返回有关实体的元数据

java - 如何在 libgdx 项目中使用 android 类?

php - 如何保存 XML 文件并将其发送到另一个页面。