Reputation: 2424
i'm trying to do this in Java without using an external library. I can't use an external library to do this because I'm not using Maven with this project.
The method i'm using is:
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;
}
}
and the error i'm getting is:
[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)
Are there some simple Java URL shortening alternatives that don't require an external jar if this method won't work? Thanks for the help!
Edit
The url for the api was wrong. updated it with new error as well.
Upvotes: 2
Views: 9810
Reputation: 1044
The 400 Bad Request error is often caused by entering or pasting the wrong URL.
As I can see in your URL the api key is missing. You can generate it from here: https://developers.google.com/url-shortener/v1/getting_started
I am using a random key, Try this code with your key and it will work:
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;
}
}
Upvotes: 3
Reputation: 356
You need to add your client key before calling the google api. something like : URL url = new URL("https://www.googleapis.com/urlshortener/v1/url?key=my_api_key");
and you need to add the google certificates to your keystore as you will be connecting to a https site
Upvotes: 0
Reputation: 448
Try this code to redirect your link to the final destination. It uses Apache HTTP Client library though. This is the only way I could successfully redirect to every valid link possible. Other methods had low accuracy for me.
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;
}
Upvotes: 3