Talk:Java

From BC$ MobileTV Wiki
Jump to: navigation, search

REST client

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

HttpClient httpClient = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(10))
        .build();                                 

try {
    String urlEndpoint = "https://postman-echo.com/get";
    URI uri = URI.create(urlEndpoint + "?foo1=bar1&foo2=bar2");
    HttpRequest request = HttpRequest.newBuilder()
            .uri(uri)
            .build();                             
    HttpResponse<String> response = httpClient.send(request,
            HttpResponse.BodyHandlers.ofString());
} catch (IOException | InterruptedException e) {
    throw new RuntimeException(e);
}

System.out.println("Status code: " + response.statusCode());                           
System.out.println("Headers: " + response.headers().allValues("content-type"));            
System.out.println("Body: " + response.body());

Using new HTTPClient code


REST server

    @XmlRootElement
        @XmlAccessorType(XmlAccessType.FIELD) 
        class Message {     
          @XmlElement 
          public final String message = "Hello World in XML"; 
        }
public class HelloWorldXml {
  public static void main(String[] args) throws JAXBException{
    JAXBContext jaxb = JAXBContext.newInstance(Message.class);
    Marshaller marshaller = jaxb.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FRAGMENT,Boolean.TRUE);
    StringWriter writer = new StringWriter();
    marshaller.marshal(new Message(), writer);
    System.out.println(writer.toString());
  } 
}

Using JAXB lib

    module com.packt{
      //depends on the java.xml.bind module
      requires java.xml.bind;
      //need this for Messages class to be available to java.xml.bind
      exports  com.packt to java.xml.bind;
    }


Java 11 syntax to compile the source, HelloWorldXml.java and module-info.java, into the mods/com.packt directory:

     javac -d mods/com.packt/ src/com.packt/module-info.java src/com.packt/com/packt/HelloWorldXml.java

Java 11 syntax to run the module-based project with dependencies:

     java --module-path mods -m com.packt/com.packt.HelloWorldXml