如何使用 google Shorter api 创建缩短 Url

发布于 2024-11-07 02:02:02 字数 5683 浏览 4 评论 0原文

我正在尝试使用谷歌缩短器 API 来缩短网址,我尝试在谷歌上找到一些可以帮助我的东西,但我没有找到博客或 java/android 上可以帮助我的东西。如果有人有更好的资源,请建议我。这是我的代码

public class tinyurl extends Activity implements OnClickListener {
EditText original;
TextView txt;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button btn = (Button) findViewById(R.id.Button01);

    original = (EditText) findViewById(R.id.edittext);
    txt = (TextView) findViewById(R.id.TextView03);
    btn.setOnClickListener(this);
}



@Override
public void onClick(View v) {
    final String GOOGL_URL = "https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyAau1E_WrYwMiTNqhK5hgH0tyWudyahbOI";
    String tinyUrl = null;
    String original = "http://www.google.com/";
    HttpTransport transport = GoogleTransport.create();
    GoogleHeaders defaultHeaders = new GoogleHeaders();
    transport.defaultHeaders = defaultHeaders;
    transport.defaultHeaders.put("Content-Type", "application/json");
    transport.addParser(new JsonHttpParser());
    HttpRequest request = transport.buildPostRequest();
    request.setUrl(GOOGL_URL);
    GenericData data = new GenericData();
    // data.put("longUrl", "http://www.google.com/");
    data.put("longUrl", original);
    JsonHttpContent content = new JsonHttpContent();

    content.data = data;
    request.content = content;

    HttpResponse response = null;
    try {
        response = request.execute();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.d("eception occured", e.toString());
    }
    Result result = null;
    try {
        result = response.parseAs(Result.class);
        Log.d("TinyUrl", result.shortUrl.toString());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

public class Result extends GenericJson {

    public String shortUrl;

}

}

由于这条线,我一直面临强制关闭。

response = request.execute();

有什么建议吗?

这是我的堆栈跟踪(如果它有任何帮助的话)。

   05-12 23:48:55.033: ERROR/AndroidRuntime(455): FATAL EXCEPTION: main
05-12 23:48:55.033: ERROR/AndroidRuntime(455): java.lang.ExceptionInInitializerError
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at com.google.api.client.json.JsonHttpContent.writeTo(JsonHttpContent.java:66)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at com.google.api.client.apache.ContentEntity.writeTo(ContentEntity.java:55)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at org.apache.http.impl.entity.EntitySerializer.serialize(EntitySerializer.java:97)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at org.apache.http.impl.AbstractHttpClientConnection.sendRequestEntity(AbstractHttpClientConnection.java:161)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at org.apache.http.impl.conn.AbstractClientConnAdapter.sendRequestEntity(AbstractClientConnAdapter.java:272)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at org.apache.http.protocol.HttpRequestExecutor.doSendRequest(HttpRequestExecutor.java:237)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:119)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:410)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at com.google.api.client.apache.ApacheHttpRequest.execute(ApacheHttpRequest.java:47)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:207)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at com.tinyurl.tinyurl.onClick(tinyurl.java:113)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at android.view.View.performClick(View.java:2408)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at android.view.View$PerformClick.run(View.java:8816)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at android.os.Handler.handleCallback(Handler.java:587)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at android.os.Handler.dispatchMessage(Handler.java:92)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at android.os.Looper.loop(Looper.java:123)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at android.app.ActivityThread.main(ActivityThread.java:4627)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at java.lang.reflect.Method.invokeNative(Native Method)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at java.lang.reflect.Method.invoke(Method.java:521)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at dalvik.system.NativeStart.main(Native Method)
05-12 23:48:55.033: ERROR/AndroidRuntime(455): Caused by: java.lang.NoClassDefFoundError: org.codehaus.jackson.JsonFactory
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at com.google.api.client.json.Json.<clinit>(Json.java:56)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     ... 25 more

i am trying to shorten a url using google shortener api, i tried my luck to find something on google that could help me but i found no blog or something that on java/android that could help me.If someone have a better resources please suggest me. Here's my code

public class tinyurl extends Activity implements OnClickListener {
EditText original;
TextView txt;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button btn = (Button) findViewById(R.id.Button01);

    original = (EditText) findViewById(R.id.edittext);
    txt = (TextView) findViewById(R.id.TextView03);
    btn.setOnClickListener(this);
}



@Override
public void onClick(View v) {
    final String GOOGL_URL = "https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyAau1E_WrYwMiTNqhK5hgH0tyWudyahbOI";
    String tinyUrl = null;
    String original = "http://www.google.com/";
    HttpTransport transport = GoogleTransport.create();
    GoogleHeaders defaultHeaders = new GoogleHeaders();
    transport.defaultHeaders = defaultHeaders;
    transport.defaultHeaders.put("Content-Type", "application/json");
    transport.addParser(new JsonHttpParser());
    HttpRequest request = transport.buildPostRequest();
    request.setUrl(GOOGL_URL);
    GenericData data = new GenericData();
    // data.put("longUrl", "http://www.google.com/");
    data.put("longUrl", original);
    JsonHttpContent content = new JsonHttpContent();

    content.data = data;
    request.content = content;

    HttpResponse response = null;
    try {
        response = request.execute();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.d("eception occured", e.toString());
    }
    Result result = null;
    try {
        result = response.parseAs(Result.class);
        Log.d("TinyUrl", result.shortUrl.toString());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

public class Result extends GenericJson {

    public String shortUrl;

}

}

all the time i am facing force close due to this line.

response = request.execute();

any suggestions?

here is my Stack trace if it gives any help.

   05-12 23:48:55.033: ERROR/AndroidRuntime(455): FATAL EXCEPTION: main
05-12 23:48:55.033: ERROR/AndroidRuntime(455): java.lang.ExceptionInInitializerError
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at com.google.api.client.json.JsonHttpContent.writeTo(JsonHttpContent.java:66)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at com.google.api.client.apache.ContentEntity.writeTo(ContentEntity.java:55)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at org.apache.http.impl.entity.EntitySerializer.serialize(EntitySerializer.java:97)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at org.apache.http.impl.AbstractHttpClientConnection.sendRequestEntity(AbstractHttpClientConnection.java:161)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at org.apache.http.impl.conn.AbstractClientConnAdapter.sendRequestEntity(AbstractClientConnAdapter.java:272)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at org.apache.http.protocol.HttpRequestExecutor.doSendRequest(HttpRequestExecutor.java:237)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:119)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:410)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at com.google.api.client.apache.ApacheHttpRequest.execute(ApacheHttpRequest.java:47)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:207)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at com.tinyurl.tinyurl.onClick(tinyurl.java:113)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at android.view.View.performClick(View.java:2408)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at android.view.View$PerformClick.run(View.java:8816)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at android.os.Handler.handleCallback(Handler.java:587)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at android.os.Handler.dispatchMessage(Handler.java:92)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at android.os.Looper.loop(Looper.java:123)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at android.app.ActivityThread.main(ActivityThread.java:4627)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at java.lang.reflect.Method.invokeNative(Native Method)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at java.lang.reflect.Method.invoke(Method.java:521)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at dalvik.system.NativeStart.main(Native Method)
05-12 23:48:55.033: ERROR/AndroidRuntime(455): Caused by: java.lang.NoClassDefFoundError: org.codehaus.jackson.JsonFactory
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     at com.google.api.client.json.Json.<clinit>(Json.java:56)
05-12 23:48:55.033: ERROR/AndroidRuntime(455):     ... 25 more

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我一向站在原地 2024-11-14 02:02:02

在堆栈跟踪的底部,您有一个 NoClassDefFoundError,这意味着您的类路径中缺少一些 jar 文件。

At the bottom of the stack trace you have a NoClassDefFoundError, which means you are missing some jar files on your classpath.

四叶草在未来唯美盛开 2024-11-14 02:02:02

我遇到了 API 问题,所以我使用了 Web API。做了下面的课程,效果很好。使用 GoogleUrlShortener 类(ShortUrlResponse 类,它只是一个解析 json 响应的 pojo)只需替换其中的 api 密钥即可:

import com.google.gson.Gson;
import com.google.gson.annotations.Expose;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class GoogleUrlShortener {

    private static final String API_KEY = "YOUR KEY HERE";

    public String shorten(String longUrl) {

        String urlString = "https://www.googleapis.com/urlshortener/v1/url?key="+API_KEY;

        String charset = "UTF-8";
        OutputStream output = null;;
        HttpURLConnection connection = null;
        Gson gson = new Gson();
        BufferedReader reader = null;
        String request="{\"longUrl\": \""+longUrl+"\"}";
        String responseString="";
        String shortUrl=longUrl; //for now
        try{

            java.net.URL url = new java.net.URL(urlString);

            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("charset", "utf-8");

            output = connection.getOutputStream();
            output.write(request.getBytes(charset));

            String line;
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuffer sb = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            responseString = sb.toString();

            shortUrl = gson.fromJson(responseString, ShortUrlResponse.class).getId();

            reader.close();

            //connection.

            int code = connection.getResponseCode();
            if (code != 200)
            {
                System.out.println("GoogleUrlShortener request failed: "+responseString);
            }


        }catch(Throwable ex)
        {
            System.out.println("GoogleUrlShortener Exception: cannot shorten url. Long url: "+longUrl+" , api response: "+responseString);
            ex.printStackTrace();

        }
        finally{
            try{
                output.close();
                reader.close();
                return shortUrl;
            }
            catch(Exception e)
            {
                System.out.println("error in closing connections. something is really wrong");
            }
        }
        return shortUrl;
    }

    public static void main(String[] args) {
        GoogleUrlShortener shortener = new GoogleUrlShortener();
        //String returned = GoogleUrlShortener.shorten("www.cnn.com");
        String returned = shortener.shorten("http://edition.cnn.com/2015/07/28/middleeast/gallery/egpyt-suez-canal-then-now/index.html");
        System.out.println("Short url returned---"+returned);

    }



    public class ShortUrlResponse {

        @Expose
        private String kind;
        @Expose
        private String id;
        @Expose
        private String longUrl;

        /**
         *
         * @return
         * The kind
         */
        public String getKind() {
            return kind;
        }

        /**
         *
         * @param kind
         * The kind
         */
        public void setKind(String kind) {
            this.kind = kind;
        }

        public ShortUrlResponse withKind(String kind) {
            this.kind = kind;
            return this;
        }

        /**
         *
         * @return
         * The id
         */
        public String getId() {
            return id;
        }

        /**
         *
         * @param id
         * The id
         */
        public void setId(String id) {
            this.id = id;
        }

        public ShortUrlResponse withId(String id) {
            this.id = id;
            return this;
        }

        /**
         *
         * @return
         * The longUrl
         */
        public String getLongUrl() {
            return longUrl;
        }

        /**
         *
         * @param longUrl
         * The longUrl
         */
        public void setLongUrl(String longUrl) {
            this.longUrl = longUrl;
        }

        public ShortUrlResponse withLongUrl(String longUrl) {
            this.longUrl = longUrl;
            return this;
        }

    }

}

I was having issues with the API so I used the web api. Made the classes below and it works fine. Use the GoogleUrlShortener class (the ShortUrlResponse class, its just a pojo to parse the json response) Just replace your api key in there:

import com.google.gson.Gson;
import com.google.gson.annotations.Expose;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class GoogleUrlShortener {

    private static final String API_KEY = "YOUR KEY HERE";

    public String shorten(String longUrl) {

        String urlString = "https://www.googleapis.com/urlshortener/v1/url?key="+API_KEY;

        String charset = "UTF-8";
        OutputStream output = null;;
        HttpURLConnection connection = null;
        Gson gson = new Gson();
        BufferedReader reader = null;
        String request="{\"longUrl\": \""+longUrl+"\"}";
        String responseString="";
        String shortUrl=longUrl; //for now
        try{

            java.net.URL url = new java.net.URL(urlString);

            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("charset", "utf-8");

            output = connection.getOutputStream();
            output.write(request.getBytes(charset));

            String line;
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuffer sb = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            responseString = sb.toString();

            shortUrl = gson.fromJson(responseString, ShortUrlResponse.class).getId();

            reader.close();

            //connection.

            int code = connection.getResponseCode();
            if (code != 200)
            {
                System.out.println("GoogleUrlShortener request failed: "+responseString);
            }


        }catch(Throwable ex)
        {
            System.out.println("GoogleUrlShortener Exception: cannot shorten url. Long url: "+longUrl+" , api response: "+responseString);
            ex.printStackTrace();

        }
        finally{
            try{
                output.close();
                reader.close();
                return shortUrl;
            }
            catch(Exception e)
            {
                System.out.println("error in closing connections. something is really wrong");
            }
        }
        return shortUrl;
    }

    public static void main(String[] args) {
        GoogleUrlShortener shortener = new GoogleUrlShortener();
        //String returned = GoogleUrlShortener.shorten("www.cnn.com");
        String returned = shortener.shorten("http://edition.cnn.com/2015/07/28/middleeast/gallery/egpyt-suez-canal-then-now/index.html");
        System.out.println("Short url returned---"+returned);

    }



    public class ShortUrlResponse {

        @Expose
        private String kind;
        @Expose
        private String id;
        @Expose
        private String longUrl;

        /**
         *
         * @return
         * The kind
         */
        public String getKind() {
            return kind;
        }

        /**
         *
         * @param kind
         * The kind
         */
        public void setKind(String kind) {
            this.kind = kind;
        }

        public ShortUrlResponse withKind(String kind) {
            this.kind = kind;
            return this;
        }

        /**
         *
         * @return
         * The id
         */
        public String getId() {
            return id;
        }

        /**
         *
         * @param id
         * The id
         */
        public void setId(String id) {
            this.id = id;
        }

        public ShortUrlResponse withId(String id) {
            this.id = id;
            return this;
        }

        /**
         *
         * @return
         * The longUrl
         */
        public String getLongUrl() {
            return longUrl;
        }

        /**
         *
         * @param longUrl
         * The longUrl
         */
        public void setLongUrl(String longUrl) {
            this.longUrl = longUrl;
        }

        public ShortUrlResponse withLongUrl(String longUrl) {
            this.longUrl = longUrl;
            return this;
        }

    }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文