Created
November 7, 2017 05:21
-
-
Save 4drianMatei/f6c9387316ed2f533a4b73f91d661212 to your computer and use it in GitHub Desktop.
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
/** | |
* In this example we'll GET a codingmark identified by its location callling the following REST resource | |
* https://www.codingmarks.org/public/codingmarks?location={myLocation} | |
* which is protected with Basic-Authentication | |
**/ | |
import javax.ws.rs.NotFoundException; | |
import javax.ws.rs.client.Client; | |
import javax.ws.rs.client.ClientBuilder; | |
import javax.ws.rs.core.MediaType; | |
import javax.ws.rs.core.Response; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.util.*; | |
........ | |
Client codingmarksApiClient = ClientBuilder.newClient(); | |
String username="test_user"; | |
String password="supersecret"; | |
String usernameAndPassword = username + ":" + password; | |
String authorizationHeaderValue = "Basic " + java.util.Base64.getEncoder().encodeToString( usernameAndPassword.getBytes() ); | |
String myLocation = "https://www.codingpedia.org//ama/jaxrs-rest-client-example-with-basic-authentication" | |
Codingmark codingmark = codingmarksApiClient | |
.target("https://www.codingmarks.org/") | |
.path("public/codingmarks") | |
.queryParam("location", location) | |
.request(MediaType.APPLICATION_JSON) | |
.header("Authorization", authorizationHeaderValue) | |
.get(Codingmark.class); | |
// Variant which returns a Response Object, which gives fine-grained control of the HTTP Response on the client side | |
Response response = codingmarksApiClient | |
.target("https://www.codingmarks.org/") | |
.path("public/codingmarks") | |
.queryParam("location", location) | |
.request(MediaType.APPLICATION_JSON) | |
.header("Authorization", authorizationHeaderValue) | |
.get(); | |
try { | |
if (response.getStatus() == 200) { | |
Codingmark codingmarkFromReponse = response.readEntity(Codingmark.class); | |
} | |
} finally { | |
response.close(); | |
/** | |
* Remember to always close() the Response objects. Response objects reference open socket streams. | |
*/ | |
} | |
/** | |
* Blog post at | |
* http://www.codingpedia.org/ama/jaxrs-rest-client-example-with-basic-authentication | |
*/ | |
......... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment