Skip to content

Instantly share code, notes, and snippets.

@drissamri
Created January 21, 2015 21:39
Show Gist options
  • Save drissamri/c5416615fbe3b8a06100 to your computer and use it in GitHub Desktop.
Save drissamri/c5416615fbe3b8a06100 to your computer and use it in GitHub Desktop.
Java client for the Linkshortener REST API
@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);
}
}
@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