2014-10-09 53 views
0

我爲android開發應用程序。 我需要發送文本並通過意圖鏈接到Twitter,但文本和鏈接太長。在網絡版本中,鏈接總是會縮短,但在應用程序中不會。有可能發送此消息嗎?我通過intent上傳的文字和網址對於twitter來說太長了

+0

http://stackoverflow.com/questions/5765747/is-it-possible-to-shorten-url-from -twitter-API – 2014-10-09 08:30:59

回答

2

在發送鏈接或文本之前使用google api shorturl ..這是我的應用程序代碼。管理你的要求。希望它會給你一個想法。

SHORTURL方法

public static String shortUrl(String data) { 
      String shortUrl = ""; 
      String serverResponse = ""; 
      try { 
       // Set connection timeout to 5 secs and socket timeout to 10 secs 
       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(
         "https://www.googleapis.com/urlshortener/v1/url"); 
       request.setHeader("Content-type", "application/json"); 
       request.setHeader("Accept", "application/json"); 

       JSONObject obj = new JSONObject(); 
       obj.put("longUrl", data); 
       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(); 
        serverResponse = out.toString(); 
       } else { 
        return null; 
       } 

       if (!Util.isNullOrEmpty(serverResponse)) { 
        JSONObject data = new JSONObject(serverResponse); 
        if (data != null) { 
         Constants.shortUrl = shortUrl = data.getString("id"); 
        } 
       } else { 
        shortUrl = shortUrl = data; 
       } 
      } catch (Exception e) { 
       shortUrl = shortUrl = data; 
      } 
      return shortUrl; 
    } 

tweeet文本

String tweetMessage = ""; 
    String shortUrl = shortUrl(String somedata); 
    if (!Util.isNullOrEmpty(shareText)){ 
     int len = shareText.length(); 
     int mlen = 140-(shortUrl.length()+8); 
     int tlen = Math.min(len, mlen); 
     String separator = " ... "; 
     if(tlen!=mlen) 
     { 
      separator = " - "; 
     } 
     tweetMessage = shareText.substring(0, tlen)+separator+shortUrl; 
    } 
    else 
    { 
     tweetMessage = "Checkout ... "+shortUrl; 
    } 


     try { 


     //send a tweet here... 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
相關問題