简体   繁体   中英

Trying to follow URL and then download image

I'm writing a java program that goes out and searches twitter, finds certain instagram links, and then downloads the instagram image to a directory. I've written all of the code to do the twitter searching and image saving but the problem that I'm having is that I get a URL in the following format

http://t.co/xxxxxxxx

From the twitter search which then if followed resolves to an instagram URL such as

http://instagr.am/p/xxxxxxxxxx/

How can I go about resolving the original URL to the instagram URL and then downloading the appropriate image on that page?

Instagram provides an API call for this. It returns everything you would need in JSON format just provide the short URL like:

http://api.instagram.com/oembed?url=http://instagr.am/p/XXXXXX/

And you'll get the data like this:

{
    provider_url: "http://instagr.am/",
    title: "Rays",
    url: "http://distillery.s3.amazonaws.com/media/2010/10/02/7e4051fdcf1d45ab9bc1fba2582c0c6b_7.jpg",
    author_name: "danrubin",
    media_id: "5382_72",
    author_id: 72,
    height: 612,
    width: 612,
    version: "1.0",
    author_url: "http://instagr.am/",
    provider_name: "Instagram",
    type: "photo"
}

Or if all you want is the image you can just add a /media to the URL:

http://instagr.am/p/XXXXXX/media

I'm not sure how much your code does, but you should be able to make an HTTP request against that t.co link, and get the Location field in the returned headers, which contains the instagr.am link.

Example header response from a t.co link:

HTTP/1.1 301 Moved Permanently
Date: Wed, 21 Mar 2012 04:48:00 GMT
Server: hi
Location: http://instagr.am/p/XXXXXX/
Cache-Control: private,max-age=300
Expires: Wed, 21 Mar 2012 04:53:00 GMT
Connection: close
Content-Type: text/html; charset=UTF-8

As you can see, the Location field is the one you want to parse out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM