bitly-api-client icon indicating copy to clipboard operation
bitly-api-client copied to clipboard

Support for v4

Open vany0114 opened this issue 5 years ago • 5 comments

Do you have plans to support the v4?

It seems this package is gonna be obsolete next March 1st

vany0114 avatar Feb 25 '20 19:02 vany0114

Do you just need to shorten urls or are you doing more advanced things like analytics? If you just need a quick way to shorten urls to bitly, let me know and I'll post the function I wrote to connect to the v4 api and get the shortened url.

hangryfabian avatar Feb 26 '20 14:02 hangryfabian

Hey @hangryfabian that would be super helpful, yeah, I just need to shorten the URL, thanks.

vany0114 avatar Feb 26 '20 14:02 vany0114

See below. I'm using a library called SimpleJSON, but you could use any other JSON library (or even work with the Strings directly). This could be much more robust / include error handling obviously. If Bitly fails for any reason, it will just return the original url.

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class URLShorteningService {

	private static final String BITLY_ACCESSTOKEN = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

	public String finalUrl = "";
	private String longUrl = "";

	public URLShorteningService(String theLongUrl) 
	{
		this.finalUrl = theLongUrl;
		this.longUrl = theLongUrl;
	}


	public void shortenLink()
	{
		final String theURLString =  "https://api-ssl.bitly.com/v4/bitlinks";
		String basicAuth = "Bearer " + BITLY_ACCESSTOKEN;

		JSONObject theJsonObjResp = null;
		HttpURLConnection connection = null;
		try
		{
			JSONObject inputJSON = new JSONObject();
			inputJSON.put("long_url", this.longUrl);
			String inputPostString = inputJSON.toString();

			URL theURL = new URL(theURLString);
			connection = (HttpURLConnection) theURL.openConnection();
			connection.setRequestProperty("Authorization", basicAuth);
			connection.setRequestProperty("Content-Type","application/json");
			connection.setRequestProperty("Accept","application/json");
			connection.setRequestMethod("POST");
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setConnectTimeout(10000);
			connection.setReadTimeout(25000);
			connection.setFixedLengthStreamingMode(inputPostString.getBytes().length);
			connection.connect();

			//Send request
			DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
			wr.write(inputPostString.getBytes());
			wr.flush ();
			wr.close ();

			//Get Response
			int status = connection.getResponseCode();
			//Utilities.log("response status is = " + status);

			String jsonString = "";
			switch (status) {
				case 200:
				case 201:
				case 202:
					//read successful response into string
					BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
					StringBuilder sb = new StringBuilder();
					String line;
					while ((line = br.readLine()) != null) {
						sb.append(line+"\n");
					}
					br.close();
					jsonString = sb.toString();
					break;
				case 400:
				case 401:
				case 402:
				case 403:
				case 404:
				case 500:
					//handle each of the different failed responses properly via https://dev.bitly.com/v4_documentation.html#section
					throw new Exception("status " + status);
			}

			try
			{
				//convert json string into json object
				JSONParser parser = new JSONParser();
				Object parsedObj = parser.parse(jsonString);
				theJsonObjResp =(JSONObject)parsedObj;
				String shortenedLinkString = scrubString ((String) theJsonObjResp.get("link"));
				//Utilities.log("shortened link = " + shortenedLinkString);
				if (shortenedLinkString.length() > 0)
					this.finalUrl = shortenedLinkString;
			}
			catch (Exception e)
			{
				//Utilities.log("bitly - failed to parse json");
				throw new Exception("Failed to parse json!");
			}

		}
		catch (Exception e)
		{
			//Utilities.logException(e, null);
		}
		finally
		{
			if (connection != null) {
				connection.disconnect();
			}
		}

	}

	private static String scrubString(String input)
	{
		if (input == null)
			return "";
		else
			return input;
	}
	
}

Then call it with:

URLShorteningService theURLService = new URLShorteningService("https://google.com");
theURLService.shortenLink();
printWriter.println(theURLService.finalUrl);

hangryfabian avatar Feb 26 '20 15:02 hangryfabian

Thanks @hangryfabian I made a function using RestTemplate, this is the code, might be helpful to someone

public class BitlyHelper {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${BITLY_TOKEN}")
    private String BITLY_TOKEN;

    private static final String endpoint = "https://api-ssl.bitly.com/v4/shorten";

    public String shorten(String longUrl){
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization", String.format("Bearer %s", BITLY_TOKEN));

        ShortenRequest request = new ShortenRequest(longUrl);
        HttpEntity<ShortenRequest> entity = new HttpEntity<>(request, headers);

        ResponseEntity<ShortenResponse> bitlyResponse = restTemplate.exchange(endpoint, HttpMethod.POST, entity, ShortenResponse.class);
        return Objects.requireNonNull(bitlyResponse.getBody()).getLink();
    }
}
class ShortenRequest{
    private String domain = "bit.ly";
    private String long_url;

    public ShortenRequest(String long_url){
        this.long_url = long_url;
    }

    public String getDomain() {
        return domain;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }

    public String getLong_url() {
        return long_url;
    }

    public void setLong_url(String long_url) {
        this.long_url = long_url;
    }
}

class  ShortenResponse{
    private String link;

    public String getLink() {
        return link;
    }

    public void setLink(String link) {
        this.link = link;
    }
}

vany0114 avatar Feb 26 '20 16:02 vany0114

Do you have plans to support the v4?

@vany0114 I don't have any plans to work on this lib because I don't use it myself at the moment and don't have time to rewrite it. Feel free to fork and publish your own updated version. I will happily redirect people to the new version.

stackmagic avatar Feb 27 '20 13:02 stackmagic