google url shortener - Java, shorten URL using goo.gl API? -
i'm trying in java without using external library. can't use external library because i'm not using maven 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 error i'm getting is:
[23:30:44 warn]: java.io.ioexception: server returned http response code: 400 url: https://www.googleapis.com/urlshortener/v1/url [23:30:44 warn]: @ sun.net.www.protocol.http.httpurlconnection.getinputstream0(httpurlconnection.java:1838) [23:30:44 warn]: @ sun.net.www.protocol.http.httpurlconnection.getinputstream(httpurlconnection.java:1439) [23:30:44 warn]: @ sun.net.www.protocol.https.httpsurlconnectionimpl.getinputstream(httpsurlconnectionimpl.java:254)
are there simple java url shortening alternatives don't require external jar if method won't work? help!
edit
the url api wrong. updated new error well.
try code redirect link final destination. uses apache http client library though. way redirect every valid link possible. other methods had low accuracy 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; }
Comments
Post a Comment