Skip to content

Instantly share code, notes, and snippets.

@felixebert
Last active June 23, 2018 10:04
Show Gist options
  • Save felixebert/12d1f637e309660dcfdd to your computer and use it in GitHub Desktop.
Save felixebert/12d1f637e309660dcfdd to your computer and use it in GitHub Desktop.
Spring Rest Template with Basic Auth + JSON - e.g. for Wordpress WP JSON API
public class RemoteApi {
protected RestTemplate restTemplate;
public RemoteApi() {
restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
}
protected HttpHeaders getHttpHeaders() {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
requestHeaders.set("Authorization", "Basic ABC==");
return requestHeaders;
}
protected HttpEntity<?> getHttpEntity() {
return new HttpEntity<Post>(getHttpHeaders());
}
public List<Post> read() {
return Arrays.asList(restTemplate.exchange("http://example.com/wp-json/posts", HttpMethod.GET, getHttpEntity(), Post[].class).getBody());
}
public Post write(Post post) {
HttpEntity<Post> httpEntity = new HttpEntity<>(post, getHttpHeaders());
ResponseEntity<Post> result = restTemplate.exchange("http://example.com/wp-json/posts/123", HttpMethod.POST, httpEntity, Post.class);
return result.getBody();
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
public class Post {
@JsonProperty("ID")
private long id;
private String title;
private String status;
private String type;
private String content;
private long parent;
private String link;
private Date date;
private Date modified;
private String standard;
private String slug;
private String guid;
private String excerpt;
@JsonProperty("ping_status")
private String pingStatus;
@JsonProperty("date_ts")
private String dateTimeZone;
@JsonProperty("date_gmt")
private Date dateGmt;
private Map<String, List<Term>> terms;
/* getter + setter */
}
@franckclement
Copy link

I have a Wordpress wp-json/posts to request through RestTemplate, but I c'ant make it work, it doesn't need any authentication, a simple GET from the browser/PostMan to the wp-json/posts actually works but through RestTemplate I get "Request Rejected The requested URL was rejected Please consult with your administrator" message :/ Any idea ?

@franckclement
Copy link

I figured it out and set "requestHeaders.set("User-Agent", "Mozilla/5.0");" to let Wordpress think i'm a browser !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment