sexta-feira, 7 de fevereiro de 2014

Marvel Java

Oi pessoal :)

A Marvel lançou o http://developer.marvel.com/ com uma API RESTful para você acessar imagens, histórias, dados entre outras coisas da Marvel.



Você pode usar isso em seu site, em jogos, num app pra celular, num aplicativo pra TV digital ou onde sua criatividade deixar :P

Fiz um client Java só para brincar, chamei ele de JMarvelRestClient, caso queiram executar aí é só criar um projeto java, um pacote br.com.localhost8080.test e colar a classe abaixo e alterar para usar suas próprias chaves no método mountUrlRest!!! Para obter as chaves é só se cadastrar lá no http://developer.marvel.com/

Nessa classe tem o client Rest e tem um método para converter uma string para MD5 para a autenticação.

A saída da execução desta classe está lá no final deste artigo. Até lá :P

package br.com.localhost8080.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

/**
 * Java Client for the Marvel Rest API
 */
public class JMarvelRestClient {

 /**
  * Call a Rest from Marvel just for test
  */
 public static void main(String[] args) {
  HttpURLConnection conn = null;
  try {
   URL url = new URL(JMarvelRestClient.mountRestUrl());

   conn = (HttpURLConnection) url.openConnection();
   conn.setRequestMethod("GET");
   conn.setRequestProperty("Accept", "application/json");

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

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

   String output = null;
   String retornoRest = "";
   while ((output = br.readLine()) != null) {
    retornoRest += output;
   }
   System.out.println("\nRest Return: " + retornoRest);

   JMarvelRestClient.mountImageUrl(retornoRest);
  } catch (MalformedURLException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   conn.disconnect();
  }

 }

 /**
  * Mount the URL with keys and hash
  */
 private static String mountRestUrl() {
  Long timeStamp = new Date().getTime();
  String privateKey = "PUT_HERE_YOUR_PRIVATE_KEY";
  String apikey = "PUT_HERE_YOUR_PUBLIC_KEY";
  String hash = JMarvelRestClient.generateHash(timeStamp + privateKey + apikey);

  String urlCompleta = "http://gateway.marvel.com/v1/public/comics/12?ts=" + timeStamp + "&apikey=" + apikey + "&hash=" + hash;

  System.out.println("Rest URL: " + urlCompleta);

  return urlCompleta;
 }

 /**
  * Makes a magic that transforms your string in MD5 hash
  */
 private static String generateHash(String string) {
  MessageDigest md = null;
  try {
   md = MessageDigest.getInstance("MD5");
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  }
  md.update(string.getBytes());
  byte[] bytes = md.digest();

  StringBuilder s = new StringBuilder();
  for (int i = 0; i < bytes.length; i++) {
   int parteAlta = ((bytes[i] >> 4) & 0xf) << 4;
   int parteBaixa = bytes[i] & 0xf;
   if (parteAlta == 0) {
    s.append('0');
   }
   s.append(Integer.toHexString(parteAlta | parteBaixa));
  }
  return s.toString();
 }

 /**
  * Master workaround to get a JSON attribute, you must do this correctly, I did this because it is more funny :)
  */
 private static void mountImageUrl(String total) {
  int inicio = total.lastIndexOf("\"thumbnail\":{\"path\":\"");
  int fim = total.indexOf("\",\"extension\":\"");
  String ss = total.substring(inicio, fim).substring(21) + "/portrait_xlarge.jpg";

  System.out.println("\nUse this URL to see the image returned by Rest: " + ss);
 }

}
Oi de novo :) Aqui está a saída desse meu código. Usei um [...] pra ficar um pouco menor.
Rest URL: http://gateway.marvel.com/v1/public/comics/12?ts=1391742038152&apikey=0458f299a5570e88176c0cd08be6a592&hash=37d71302dc8fcbb7a67fab5c25dadc71

Rest Return: {"code":200,"status":"Ok","etag":"e41c5cc5be95cd99d46ec56146f1051099c9abb5","data":{"offset":0,"limit":20,"total":1,"count":1,"results":[{"id":12,"digitalId":4089,"title":"Ultimate Spider-Man (2000) #68","issueNumber":68,"variantDescription":"","description":"SUPERSTARS PART 3 Johnny Storm still doesn't have a high school
[...]
Torch","type":"interiorStory"}],"returned":2},"events":{"available":0,"collectionURI":"http://gateway.marvel.com/v1/public/comics/12/events","items":[],"returned":0}}]}}

Use this URL to see the image returned by Rest: http://i.annihil.us/u/prod/marvel/i/mg/f/90/4bc6b6e773bde/portrait_xlarge.jpg
Pelo Rest recebemos uma URL de uma imagem (mais detalhes em http://developer.marvel.com/documentation/images)

Bom, é isso, qualquer dúvida posta aí que tentarei ajudar!

Fontes:
http://www.mkyong.com/webservices/jax-rs/restfull-java-client-with-java-net-url/
http://codare.net/2007/02/02/java-gerando-codigos-hash-md5-sha/

Abraços!
Adriano Schmidt

Nenhum comentário:

Postar um comentário