JAX RS – 32 – HTTP Content Negotiation – 02

Merhaba Arkadaslar
Bu bolumde HTTP Content Negotiation bolumune devam ediyoruz.

Onceki bolumlerde @Produces annotation’ini kullanmistik. @Produces annotation da MediaType degerlerini kullanarak donus/response un tipini belirtiyorduk.

Ornek kodumuzu inceleyelim , 3 metot icin de URI adresi ayni olacak.

CustomerResource.java

package _25.content.negotiation.service;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import _25.content.negotiation.model.Customer;

@Path("/customer-negotiation")
public class CustomerResource {

	@GET
	@Path("/customer")
	@Produces(MediaType.TEXT_HTML)
	public String getCustomerText() {
		System.out.println("getCustomerText is invoked.");
		return new Customer(1, "Levent").toString();
	}

	@GET
	@Path("/customer")
	@Produces(MediaType.APPLICATION_JSON)
	public Customer getCustomerJSON() {
		System.out.println("getCustomerJSON is invoked.");
		return new Customer(1, "Levent");
	}

	@GET
	@Path("/customer")
	@Produces(MediaType.APPLICATION_XML)
	public Customer getCustomerXML() {
		System.out.println("getCustomerXML is invoked.");
		return new Customer(1, "Levent");
	}
}

Ornegimizi calistirdigimizda ;
hebele
getCustomerText metodumuz istegi karsilayacaktir.

Eclipse Console’da

getCustomerText is invoked.

Network bolumunde inceleyecek olursak Accept header’i ;

text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8

Bu durumda oncelik siralamasinda text/html 1.sirada yer alacaktir.
Dolayisiyla @Produces(MediaType.TEXT_HTML) olarak MediaType belirttigimiz metot istegi karsilayacaktir.

Advanced Rest Client ile , Accept header bilgisi ekleyip test edebiliriz.

application/json

Bir baska ornek olarak q parametresi ile test edelim ;
q parametresine onceki bolumde deginmistik. Burada application/xml degeri icin q degeri 1.0 olduug icin oncelik olarak XML formati secilecektir.

Bir baska ornek kod olarak;
@Produces annotation da hem JSON hem XML icin MediaType ekleyelim.

	@GET
	@Path("/customerXMLOrJSON")
	@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
	public Customer getCustomerXMLOrJSON() {
		System.out.println("customerXMLOrJSON is invoked.");
		return new Customer(1, "Levent");
	}

Accept header ;

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8

Bu nedenle oncelik application/xml olacaktir.
Tabi Accept header olarak application/json parametresi eklersek bu durumda donus JSON formatinda olacaktir.

Github kaynak kodlar / source folder
injavawetrust.resteasy
injavawetrust.jersey

Yazimi burada sonlandiriyorum.
Herkese Bol Javali Gunler dilerim.

Print Friendly, PDF & Email

Leave a Reply

Your email address will not be published. Required fields are marked *