2011-08-24 10 views
15

Qui non sto creando un servizio RESTful infatti 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 parser SAX, ho sentito che possiamo usare JAX-RS e JERSEY che mappano automaticamente i tag xml agli oggetti java corrispondenti.chiama Restful Service from Java

Ho cercato ma non riesco a trovare una fonte per iniziare. ho guardato i collegamenti esistenti Consuming RESTful APIs using Java RESTful call in Java

ogni aiuto è apprezzato in movimento in avanti.

Grazie !!

+0

se si può chiamare il servizio e ottenere JSON indietro invece, il GSON/Jackson Apis sono più facili di JAXB, nel senso che non è necessario annotazioni sul modello di oggetti – Kevin

+0

Ciao Kevin, ho un servizio REST esterna e voglio chiamarlo dall'app web. Qual'è il miglior modo di farlo? Il servizio REST restituisce il formato JSON come risposta. hai detto che è facile gestire la risposta JSON. Puoi spiegare come? – Jignesh

risposta

16

UPDATE

come follow-up con questo: Posso fare in questo modo ?? se il xml viene restituito come 4 ..... Se sto costruendo un oggetto Person, credo che questo si strozzerà. Posso solo associare solo gli elementi xml che voglio? se sì, come posso fare quello.

Potreste 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 chiamare un servizio RESTful utilizzando le API di Java SE, tra cui 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 ulteriori informazioni:

+1

come follow-up con questo: Posso fare in questo modo ?? se l'XML viene restituito come 4 ..... Se sto costruendo un oggetto Person , Credo che questo si strozzerà. Posso solo associare solo gli elementi xml che voglio? se sì, come posso farlo? – Rishi

6

JAX-RS è l'API Java per webservice riposante. Jersey è un'implementazione da sun/oracle.

È necessario jaxb convertire il tuo xml in un POJO. Ma non è sempre il caso che l'oggetto convertito possa essere usato senza alcuna trasformazione. Se questo è lo scenario, SAXParser è una buona soluzione.

Here è un bel tutorial su JAXB.

3

Io uso Apache CXF per creare i miei servizi RESTful, che è un'altra implementazione JAX-RS (fornisce anche un'implementazione JAX-WS). Io uso anche la sua classe "org.apache.cxf.jaxrs.client.WebClient" nei test unitari, che gestiranno completamente tutti i marshalling e unmarshalling sotto le coperte. Gli dai un URL e chiedi un oggetto di un tipo particolare, e fa tutto il lavoro. Non so se Jersey ha strutture simili.

1

Se hai bisogno anche di convertire tale stringa XML che si presenta come una risposta alla chiamata di servizio, un oggetto x è necessario può farlo nel seguente modo:

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

}

Nota che la struttura XML che mi aspettavo l'esempio è stato il seguente:

<ciudad><idCiudad>1</idCiudad><nomCiudad>BOGOTA</nomCiudad></ciudad>