chiamata del servizio Restful da Java


Qui non sto creando un servizio RESTful, anzi devo chiamare un servizio Restful esterno dal mio codice java. Attualmente sto implementando questo usando Apache HttpClient. La risposta che ottengo dal servizio web è in formato XML. Ho bisogno di estrarre i dati da XML e metterli su oggetti Java. Piuttosto che usare il parser SAX, ho sentito che possiamo usare JAX-RS e JERSEY che mappano automaticamente i tag xml agli oggetti java corrispondenti.

Ho guardato attraverso ma incapace per trovare una fonte per iniziare. Ho guardato i link esistenti Utilizzo di API RESTful utilizzando Java Chiamata restful in Java

Qualsiasi aiuto è apprezzato per andare avanti.

Grazie!!

Author: Community, 2011-08-24

5 answers

AGGIORNAMENTO

Come segue: posso fare in questo modo?? se l'xml viene restituito as 4 ..... Se sto costruendo un oggetto Persona, credo che questo si soffocherà. Posso semplicemente associare solo gli elementi xml che voglio? se sì come posso fare quello.

È possibile mappare questo XML come segue:

Ingresso.xml

<?xml version="1.0" encoding="UTF-8"?>
<Persons>
    <NumberOfPersons>2</NumberOfPersons>
        <Person>
            <Name>Jane</Name>
            <Age>40</Age>
        </Person>
        <Person>
            <Name>John</Name>
            <Age>50</Age>
        </Person>
</Persons> 

Persone

package forum7177628;

import java.util.List;

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

@XmlRootElement(name="Persons")
@XmlAccessorType(XmlAccessType.FIELD)
public class Persons {

    @XmlElement(name="Person")
    private List<Person> people;

}

Persona

package forum7177628;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;

@XmlAccessorType(XmlAccessType.FIELD)
public class Person {

    @XmlElement(name="Name")
    private String name;

    @XmlElement(name="Age")
    private int age;

}

Demo

package forum7177628;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Persons.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Persons persons = (Persons) unmarshaller.unmarshal(new File("src/forum7177628/input.xml"));

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(persons, System.out);
    }

}

Uscita

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Persons>
    <Person>
        <Name>Jane</Name>
        <Age>40</Age>
    </Person>
    <Person>
        <Name>John</Name>
        <Age>50</Age>
    </Person>
</Persons>

RISPOSTA ORIGINALE

Di seguito è riportato un esempio di chiamata di un servizio RESTful utilizzando le API Java SE incluso JAXB:

String uri =
    "http://localhost:8080/CustomerService/rest/customers/1";
URL url = new URL(uri);
HttpURLConnection connection =
    (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");

JAXBContext jc = JAXBContext.newInstance(Customer.class);
InputStream xml = connection.getInputStream();
Customer customer =
    (Customer) jc.createUnmarshaller().unmarshal(xml);

connection.disconnect();

Per maggiori informazioni:

 16
Author: Blaise Doughan, 2011-08-24 17:19:19

JAX-RS è l'api Java per il servizio Web restful. Jersey è un'implementazione di sun/oracle.

Hai bisogno di jaxb per convertire il tuo xml in un POJO. Ma non è sempre il caso che, oggetto convertito può essere utilizzato senza alcuna trasformazione. Se questo è lo scenario SAXParser è una bella soluzione.

Qui è un bel tutorial su JAXB.

 6
Author: Kowser, 2011-08-24 15:13:49

Potresti considerare l'utilizzo di jaxb per associare i tuoi oggetti java a un documento xml (marshalling).

Http://www.oracle.com/technetwork/articles/javase/index-140168.html#xmp1

 4
Author: Snicolas, 2012-02-28 12:05:47

Io uso Apache CXF per costruire i miei servizi RESTful, che è un'altra implementazione JAX-RS (fornisce anche un'implementazione JAX-WS). Uso anche il suo "org.Apache.cxf.jaxrs.cliente.Classe "WebClient" nei test unitari, che gestirà completamente tutto il marshalling e lo unmarshalling sotto le coperte. Gli dai un URL e chiedi un oggetto di un tipo particolare, e fa tutto il lavoro. Non lo so se Jersey ha strutture simili.

 3
Author: David M. Karr, 2011-08-24 15:21:49

Se devi anche convertire quella stringa xml che viene fornita come risposta alla chiamata di servizio, un oggetto x di cui hai bisogno può farlo come segue:

 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStreamReader;
 import java.io.StringReader;
 import java.net.HttpURLConnection;
 import java.net.MalformedURLException;
 import java.net.URL;
 import java.util.ArrayList;
 import java.util.List;

 import javax.xml.bind.JAXB;
 import javax.xml.bind.JAXBException;
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;

 import org.w3c.dom.CharacterData;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
 import org.xml.sax.InputSource;
 import org.xml.sax.SAXException;

 public class RestServiceClient {

// http://localhost:8080/RESTfulExample/json/product/get
public static void main(String[] args) throws ParserConfigurationException,
    SAXException {

try {

    URL url = new URL(
        "http://localhost:8080/CustomerDB/webresources/co.com.mazf.ciudad");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Accept", "application/xml");

    if (conn.getResponseCode() != 200) {
    throw new RuntimeException("Failed : HTTP error code : "
        + conn.getResponseCode());
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(
        (conn.getInputStream())));

    String output;

    Ciudades ciudades = new Ciudades();
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
    System.out.println("12132312");
    System.err.println(output);

    DocumentBuilder db = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(output));

    Document doc = db.parse(is);
    NodeList nodes = ((org.w3c.dom.Document) doc)
        .getElementsByTagName("ciudad");

    for (int i = 0; i < nodes.getLength(); i++) {
        Ciudad ciudad = new Ciudad();
        Element element = (Element) nodes.item(i);

        NodeList name = element.getElementsByTagName("idCiudad");
        Element element2 = (Element) name.item(0);

        ciudad.setIdCiudad(Integer
            .valueOf(getCharacterDataFromElement(element2)));

        NodeList title = element.getElementsByTagName("nomCiudad");
        element2 = (Element) title.item(0);

        ciudad.setNombre(getCharacterDataFromElement(element2));

        ciudades.getPartnerAccount().add(ciudad);
    }
    }

    for (Ciudad ciudad1 : ciudades.getPartnerAccount()) {
    System.out.println(ciudad1.getIdCiudad());
    System.out.println(ciudad1.getNombre());
    }

    conn.disconnect();

} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
}

public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
    CharacterData cd = (CharacterData) child;
    return cd.getData();
}
return "";
}

}

Si noti che la struttura xml che mi aspettavo nell'esempio era la seguente:

 <ciudad><idCiudad>1</idCiudad><nomCiudad>BOGOTA</nomCiudad></ciudad>       
 1
Author: Miguel Zapata, 2016-12-09 17:24:44