1. REST resource almak için bir adrese gidelim : http://graph.facebook.com/pivotalsoftware
Gelen cevap aşağıdaki gibi bir JSON olacak:
{
- id: "161112704050757",
- about: "Pivotal is enabling the creation of modern software applications that leverage big & fast data – on a single, cloud independent platform.",
- awards: "CTO Award: Innovation Battle Hack Morgan Stanley Leadership Award: Global Commerce Bossie Awards 2013: The best open source data center and cloud software 2013 Technology Innovator of the Year CTO Award for Innovation: Greenplum DatabaseColorado’s 5 best tech companies for new developers ",
- can_post: false,
- category: "Internet/software",
- category_list:
- id: "108472109230615",
- name: "Computer Services"
- checkins: 90,
...
2. JSON içinden sadece işimize yarayan bilgileri (isim, hakkında, telefon, web adresi) çekmek için bir Page.java yazıyoruz:
package hello;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Page {
private String name;
private String about;
private String phone;
private String website;
public String getName() {
return name;
}
public String getAbout() {
return about;
}
public String getPhone() {
return phone;
}
public String getWebsite() {
return website;
}
}
3. Executable yaratabilmek için içinde bir main() metodu olan bir Application.java yazıyoruz:
package hello; import org.springframework.web.client.RestTemplate; public class Application { public static void main(String args[]) { RestTemplate restTemplate = new RestTemplate(); Page page = restTemplate.getForObject("http://graph.facebook.com/pivotalsoftware", Page.class); System.out.println("Name: " + page.getName()); System.out.println("About: " + page.getAbout()); System.out.println("Phone: " + page.getPhone()); System.out.println("Website: " + page.getWebsite()); } }4. RestTemplate Jackson JSON kütüphanesini kullanarak JSON datayı bir Page nesnesine çeviriyor.
Daha sonra oluşan Page nesnesi ekrana yazdırılıyor.
Projeyi build ve run edelim:
Gradle : ./gradlew bootRun
Maven : mvn spring-boot:run
Şu çıktıyı görüyoruz:
Name: Pivotal About: At Pivotal, our mission is to enable customers to build a new class of applications, leveraging big and fast data, and do all of this with the power of cloud independence. Phone: 650-286-8012 Website: http://www.gopivotal.com
Böylece Spring ile basit bir REST client yazmış olduk.
Hiç yorum yok:
Yorum Gönder