Created
January 21, 2015 21:39
-
-
Save drissamri/c5416615fbe3b8a06100 to your computer and use it in GitHub Desktop.
Java client for the Linkshortener REST API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@RestController | |
public class LinkController { | |
private LinkService linkService; | |
@Autowired | |
public LinkController(LinkService linkService) { | |
this.linkService = linkService; | |
} | |
@RequestMapping("/links") | |
public Link createLink(@RequestParam(value = "longUrl") String longUrl) { | |
return linkService.createLink(longUrl); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Service | |
public class LinkServiceImpl implements LinkService { | |
private RestTemplate restTemplate; | |
@Autowired | |
public LinkServiceImpl(RestTemplate restTemplate) { | |
this.restTemplate = restTemplate; | |
} | |
@Override | |
public Link createLink(String longUrl) { | |
RestTemplate restTemplate = new RestTemplate(); | |
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); | |
parameters.add("url", longUrl); | |
ResponseEntity<Link> response; | |
Link result = null; | |
try { | |
response = restTemplate.postForEntity( | |
"http://localhost:9080/api/v1/links", | |
parameters, | |
Link.class); | |
if (HttpStatus.CREATED == response.getStatusCode() || HttpStatus.OK == response.getStatusCode()) { | |
result = response.getBody(); | |
} | |
} catch (RestClientException ex) { | |
throw new RuntimeException(ex); | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment