【问题标题】:Shorter URL with Google Play Service使用 Google Play 服务的网址更短
【发布时间】:2014-09-27 17:21:41
【问题描述】:

有没有办法在 Android 上缩短 URL。我在 Google Play 服务库 (https://code.google.com/p/google-api-java-client/) 上注意到了一些东西

或者我应该使用 HTTP POST 来获取新的 URL?

提前致谢!

【问题讨论】:

    标签: android google-api google-play-services google-api-java-client url-shortener


    【解决方案1】:

    1º 在 Manifest 中授予 Internet 权限。

    2º 在 AsyncTask 中使用这个函数:

    private final String GOOGLE_URL = "https://www.googleapis.com/urlshortener/v1/url";
    
    public static String getShortUrl( String _url ){
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 5000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        int timeoutSocket = 10000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    
        HttpClient hc = new DefaultHttpClient(httpParameters);
    
        HttpPost request = new HttpPost(GOOGLE_URL);
        request.setHeader("Content-type", "application/json");
        request.setHeader("Accept", "application/json");
    
        JSONObject obj = new JSONObject();
        obj.put("longUrl", _url);
        request.setEntity(new StringEntity(obj.toString(), "UTF-8"));
    
        HttpResponse response = hc.execute(request);
    
        if ( response.getStatusLine().getStatusCode() == HttpStatus.SC_OK )
        {
         ByteArrayOutputStream out = new ByteArrayOutputStream();
         response.getEntity().writeTo(out);
         out.close();              
         return out.toString();
        }
        else {
         return null;
        }
       }
       catch ( Exception e ) {
        e.printStackTrace();        
       }
       return null;
    }  
    

    【讨论】:

    • 是的,不需要 Google Play 服务
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 2013-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多