1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
import java.net.URI; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONObject; public class Main { public static final String subscriptionKey = "Clave del API"; public static final String uriBase = "https://westcentralus.api.cognitive.microsoft.com/vision/v1.0/analyze"; public static void main(String[] args) { HttpClient httpclient = new DefaultHttpClient(); try { URIBuilder builder = new URIBuilder(uriBase); // Valores que se añaden a la URI builder.setParameter("visualFeatures", "Categories,Description,Color"); builder.setParameter("language", "en"); // Preparar la URI para la llamada REST API URI uri = builder.build(); HttpPost request = new HttpPost(uri); // Componer las Cabeceras request.setHeader("Content-Type", "application/json"); request.setHeader("Ocp-Apim-Subscription-Key", subscriptionKey); // Componer el Body StringEntity reqEntity = new StringEntity("{\"url\":\"http://www.abc.es/media/motor/2017/09/26/[email protected]\"}"); request.setEntity(reqEntity); // Ejecutar la peticióni REST API con los valores HttpResponse response = httpclient.execute(request); HttpEntity entity = response.getEntity(); if (entity != null) { // Obtener resultado JSON String jsonString = EntityUtils.toString(entity); JSONObject json = new JSONObject(jsonString); // Obtener la descripción de la imagen System.out.println(json.get("description")); } } catch (Exception e) { // Mostrar mensajes de error si salta excepción System.out.println(e.getMessage()); } } } |