2013-08-22 17 views
5

Dopo aver tentato di importare le librerie da solo, sono finalmente riuscito a scoprire che posso farlo utilizzando Google Plugin per Eclipse, here.Come faccio a utilizzare l'API Shortener dell'URL di Google su Android?

Tuttavia, non riesco a trovare alcun esempio di come utilizzare effettivamente l'API su Android, almeno nessuno che sia compilabile, in quanto le classi richieste in quegli esempi sembrano non essere risolvibili da Eclipse, quindi posso supponiamo solo che queste classi non esistano nelle librerie che vengono importate da Google Plugin per Eclipse per l'API Shortener URL. La cosa più simile a un esempio che ho trovato è here, che sembra essere per Google App Engine, non per Android, e utilizza le classi a cui non riesco a ottenere l'accesso.

Quindi la domanda è: come utilizzare questa API per ottenere una versione abbreviata di un URL, in un'applicazione Android? Preferibilmente, mi piacerebbe farlo usando una chiave API, invece di OAuth.

risposta

4
  1. aggiungere al vostro manifesta application nodo:
<meta-data 
     android:name="com.google.android.urlshortener.API_KEY" 
     android:value="{YOUR_API_KEY}"/> 
  1. add folowing librerie:

Google- api-client-1.17.0-rc.jar

google-api-client-android-1.17.0-rc.jar google-API-servizi-urlshortener-V1-rev22-1.17.0-rc.jar

google-http-client -1.17.0-rc.jar

google-http-client-android-1.17.0-rc.jar

  1. metodo:

    String shorten(String longUrl){ 
    
        Urlshortener.Builder builder = new Urlshortener.Builder (AndroidHttp.newCompatibleTransport(), AndroidJsonFactory.getDefaultInstance(), null); 
        Urlshortener urlshortener = builder.build(); 
    
        com.google.api.services.urlshortener.model.Url url = new Url(); 
        url.setLongUrl(longUrl); 
        try { 
         url = urlshortener.url().insert(url).execute(); 
         return url.getId(); 
        } catch (IOException e) { 
         return null; 
        } 
    } 
    
+0

Ho usato questo senza aggiungere nulla al manifesto e funzionava ancora. –

+1

C'è un modo per long l'URL da breve? – Anirban

+1

Invece di aggiungere tutte queste librerie, sto solo inviando una richiesta per ottenere un breve URL. Funziona bene. Per favore suggerirmi quale usare? –

3

Ora la API più breve di Google ha bisogno di una chiave per funzionare. Ho provato a impostare la chiave in manifest ma non funziona. La chiave dovrebbe essere impostata dalla libreria delle funzioni.

Urlshortener.Builder builder = new Urlshortener.Builder (AndroidHttp.newCompatibleTransport(), 
      AndroidJsonFactory.getDefaultInstance(), null); 
    Urlshortener urlshortener = builder.build(); 

    com.google.api.services.urlshortener.model.Url url = new com.google.api.services.urlshortener.model.Url(); 
    url.setLongUrl(longUrl); 
    try { 
     Urlshortener.Url.Insert insert=urlshortener.url().insert(url); 
     insert.setKey("Your API KEY"); 
     url = insert.execute(); 
     return url.getId(); 
    } catch (IOException e) { 
     LogUtil.e(TAG, Log.getStackTraceString(e)); 
     return null; 
    } 
5

Innanzitutto creare un progetto su console google e abilitare URL Shortner api e ottenere chiave API e l'uso il seguente AsyncTask per ottenere URL abbreviato.

public class newShortAsync extends AsyncTask<Void,Void,String> { 

     String longUrl="http://stackoverflow.com/questions/18372672/how-do-i-use-the-google-url-shortener-api-on-android/20406915"; 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      progressBar.setVisibility(View.VISIBLE); 
     } 

     @Override 
     protected void onPostExecute(String s) { 
      super.onPostExecute(s); 
      progressBar.setVisibility(View.GONE); 
      System.out.println("JSON RESP:" + s); 
      String response=s; 
      try { 
       JSONObject jsonObject=new JSONObject(response); 
       id=jsonObject.getString("id"); 
       System.out.println("ID:"+id); 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
     } 

     @Override 
     protected String doInBackground(Void... params) { 
      BufferedReader reader; 
      StringBuffer buffer; 
      String res=null; 
      String json = "{\"longUrl\": \""+longUrl+"\"}"; 
      try { 
       URL url = new URL("https://www.googleapis.com/urlshortener/v1/url?key=YOUR_API_KEY"); 
       HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
       con.setReadTimeout(40000); 
       con.setConnectTimeout(40000); 
       con.setRequestMethod("POST"); 
       con.setRequestProperty("Content-Type", "application/json"); 
       OutputStream os = con.getOutputStream(); 
       BufferedWriter writer = new BufferedWriter(
         new OutputStreamWriter(os, "UTF-8")); 

       writer.write(json); 
       writer.flush(); 
       writer.close(); 
       os.close(); 

       int status=con.getResponseCode(); 
       InputStream inputStream; 
       if(status==HttpURLConnection.HTTP_OK) 
       inputStream=con.getInputStream(); 
       else 
        inputStream = con.getErrorStream(); 

       reader= new BufferedReader(new InputStreamReader(inputStream)); 

       buffer= new StringBuffer(); 

       String line=""; 
       while((line=reader.readLine())!=null) 
       { 
        buffer.append(line); 
       } 

       res= buffer.toString(); 

      } catch (MalformedURLException e) { 
       e.printStackTrace(); 
      } catch (ProtocolException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      return res; 




     } 
    } 

e poi basta eseguire questo AsyncTask avrete una risposta in JSON in cui id è presente, che non è altro che URL abbreviato.

+0

Grazie @Satish –

+0

ua welcome @ParthAnjaria –

+0

{"errore": {"messaggio": "Valore non valido", "codice": 400, "errori": [{"messaggio": "Valore non valido", "dominio" : "global", "location": "resource.longUrl", "reason": "invalid", "locationType": "parameter"}]}} help me! –

0

È inoltre possibile utilizzare Gradle apparentemente

repositories { 
mavenCentral() 
} 

dependencies { 
compile 'com.google.apis:google-api-services-urlshortener:v1-rev47-1.22.0' 
} 

Google Shortner java gradle documentation