2

我试图在不使用外部库的情况下在 Java 中执行此操作。我不能使用外部库来执行此操作,因为我没有在这个项目中使用 Maven。

我使用的方法是:

public static String shorten(String longUrl) {
    if (longUrl == null) {
        return longUrl;
    }

    StringBuilder sb = null;
    String line = null;
    String urlStr = longUrl;

    try {
        URL url = new URL("https://www.googleapis.com/urlshortener/v1/url");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("User-Agent", "toolbar");

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write("url=" + URLEncoder.encode(urlStr, "UTF-8"));
        writer.close();

        BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        sb = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            sb.append(line + '\n');
        }

        String json = sb.toString();
        return json.substring(json.indexOf("http"), json.indexOf("\"", json.indexOf("http")));
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return longUrl;
    } catch (IOException e) {
        e.printStackTrace();
        return longUrl;
    }
}

我得到的错误是:

[23:30:44 WARN]: java.io.IOException: Server returned HTTP response code: 400 for URL: https://www.googleapis.com/urlshortener/v1/url
[23:30:44 WARN]:    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1838)
[23:30:44 WARN]:    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1439)
[23:30:44 WARN]:    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)

如果此方法不起作用,是否有一些不需要外部 jar 的简单 Java URL 缩短替代方案?谢谢您的帮助!

编辑

api 的 url 错误。也用新的错误更新了它。

4

3 回答 3

3

尝试使用此代码将您的链接重定向到最终目的地。它虽然使用 Apache HTTP 客户端库。这是我可以成功重定向到每个可能的有效链接的唯一方法。其他方法对我来说准确性很低。

private static String linkCorrector(String link) throws ClientProtocolException, IOException{
        HttpClient client = new DefaultHttpClient();
        HttpParams params = client.getParams();
        HttpClientParams.setRedirecting(params, false);
        HttpGet method = new HttpGet(link);
        HttpResponse resp = client.execute(method);
        String location = null;
        Header h = resp.getLastHeader("Location");
        if(h == null || h.getValue() == null){
            location = "";
        }
        else{
            location = resp.getLastHeader("Location").getValue();
        }
        return location;
    }
于 2014-06-27T06:38:08.437 回答
3

400 Bad Request 错误通常是由输入或粘贴错误的 URL 引起的。正如我在您的 URL 中看到的,缺少 api 密钥。您可以从这里生成它:https ://developers.google.com/url-shortener/v1/getting_started 在此处输入图像描述

我正在使用随机密钥,请使用您的密钥尝试此代码,它将起作用:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

import org.apache.commons.lang.StringUtils;

import flexjson.JSONDeserializer;
import flexjson.JSONSerializer;


public class URLShortnerUtil
{

    private static final String GOOGLE_SHORTEN_URL = "https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyDLEgrM8I3N3yn8pNhBaZizY";    //replace key's value with your key

    public static String shortURL(String longURL)
    {
        String shortURL = "";
        HttpsURLConnection con = null;
        try
        {
            Map<String, String> valueMap = new HashMap<>();
            valueMap.put("longUrl", longURL);
            String requestBody = new JSONSerializer().serialize(valueMap);
            con = (HttpsURLConnection) new URL(GOOGLE_SHORTEN_URL).openConnection();
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json");
            con.getOutputStream().write(requestBody.getBytes());
            if (con.getResponseCode() == 200)
            {
                StringBuilder sb = new StringBuilder();
                try(BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())))
                {
                    String line;
                    while((line = br.readLine()) != null)
                    {
                        sb.append(line);
                    }
                    Map<String, String> map = new JSONDeserializer<Map<String, String>>().deserialize(sb.toString());

                    if (map != null && StringUtils.isNotEmpty(map.get("id")))
                    {
                        shortURL = map.get("id");
                        return shortURL;
                    }
                }
                catch(IOException e)
                {
                    e.printStackTrace(); 
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace(); 
        }
        return shortURL;

    }

}
于 2018-03-21T06:46:27.700 回答
0

您需要在调用 google api 之前添加您的客户端密钥。类似于: URL url = new URL(" https://www.googleapis.com/urlshortener/v1/url?key=my_api_key ");

并且您需要将 google 证书添加到您的密钥库,因为您将连接到 https 站点

于 2014-06-27T08:06:08.207 回答