9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaからGoogleの短縮URLを生成

Last updated at Posted at 2014-10-20

以下、ソースコード貼ります。


    /**
	 * 短縮URL生成
	 * @param longUrl
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	@SuppressWarnings("resource")
	private static String getShortUrl(String longUrl) throws ClientProtocolException, IOException {
		HttpPost post = new HttpPost("https://www.googleapis.com/urlshortener/v1/url");
		post.setHeader("Content-Type", "application/json");
		post.setEntity(new StringEntity("{'longUrl': '"+longUrl+"'}", "UTF-8"));
		 
		HttpResponse response = new DefaultHttpClient().execute(post);
		 
		String responseText = EntityUtils.toString(response.getEntity());
		
		
		// JsonFactoryの生成
		JsonFactory factory = new JsonFactory();
		// JsonParserの取得
		@SuppressWarnings("deprecation")
		JsonParser parser = factory.createJsonParser(responseText);
		 
		//JSONのパース処理
		String shotUrl = "";
		while (parser.nextToken() != JsonToken.END_OBJECT) {
			String name = parser.getCurrentName();
			if (name != null) {
				parser.nextToken();
				if (name.equals("id")) {
					shotUrl = parser.getText();
				}
			}
		}
		
		return shotUrl;
	}
9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?