1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
| import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
public class TinyUrl {
private String longUrl;
private String shortUrl;
public TinyUrl() {
}
public String getLongUrl() {
return longUrl;
}
public void setLongUrl(String longUrl) {
this.longUrl = longUrl;
}
public String getShortUrl() {
return this.shorten(this.getLongUrl());
}
public void setShortUrl(String shortUrl) {
this.shortUrl = shortUrl;
}
private String shorten(String url) {
HttpClient client = new HttpClient();
client.getHostConfiguration().setHost("tinyurl.com", 80, "http");
PostMethod post = new PostMethod("/create.php");
post.addParameter(new NameValuePair("url", url));
String s = null;
try {
client.executeMethod(post);
s = post.getResponseBodyAsString();
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
int start = s.indexOf("The following URL:");
int end = s.indexOf("Open in new window");
s = s.substring(start, end);
start = s.indexOf("http://tinyurl.com");
end = s.indexOf("</b><p>");
s = s.substring(start, end);
return s;
}
public static void main(String[] args) throws HttpException, IOException {
TinyUrl tbean = new TinyUrl();
tbean.setLongUrl("http://www.google.com.tw");
System.out.println(tbean.getShortUrl());
}
}
|