I have successfully wrote HTTP request sending using Restlet's ClientResource:
public static String get(String url) {
ClientResource clientResource = new ClientResource(url);
Representation responseRepresentation = clientResource.get();
String response = responseRepresentation.getText();
return response;
}
Now I'm trying to write HTTPS requests GET and POST with Restlet's ClientResource but I'm not sure about the exact syntax.
Any reference and/or examples will be appreciated.
Related
I'm trying to consume an external api exposed a payment provider.
I user Jersey and javax.ws.rs for request, because I can easily send authent with Digest.
But when it comes to make the request, a GET with payload, Jersey returns
> IllegalStateException. Entity must be null for http method GET
CashTransactionResponse responseData = null;
//We connect to intouch server
String requestUrl = rootUrlTouchPay + agency.getAgencyCode() + "/" + IntouchMethodApis.TRANSACTION + "?loginAgent=" + agency.getLogin() + "&passwordAgent=" + agency.getPassword();
ClientConfig clientConfig = new ClientConfig();
//Open Digest authentication
HttpAuthenticationFeature feature = HttpAuthenticationFeature.digest(BASIC_LOGIN, BASIC_PWD);
clientConfig.register(feature);
clientConfig.register(JacksonFeature.class);
//Create new rest client
Client client = ClientBuilder.newClient(clientConfig);
clientConfig.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
//Set the url
WebTarget webTarget = client.target(requestUrl);
Invocation.Builder invocationBuilder = webTarget.request(javax.ws.rs.core.MediaType.APPLICATION_JSON);
logger.info("Initialisation of cashout service successful for cash");
// create request
Gson gson = new Gson();
String transactionString = gson.toJson(cashRequest);
Response response = null;
// start the response
if (cashRequest.getServiceCode().contains(TelecomEnum.WAVE.name().toUpperCase())) {
response = invocationBuilder.method("GET", Entity.entity(transactionString, javax.ws.rs.core.MediaType.APPLICATION_JSON));
} else {
response = invocationBuilder.put(Entity.entity(transactionString, javax.ws.rs.core.MediaType.APPLICATION_JSON));
}
Please how could i do to send my GET request with body ?
Thanks
I believe the problem is in
Client client = ClientBuilder.newClient(clientConfig);
clientConfig.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
The client copied the values from clientConfig and any further settings on clientConfig do not have any impact on the client.
Either switch the lines or set the ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION property on the client.
Instead of doing an invocationBuilder.method("GET", ...), use invocationBuilder.post(entity), as described here. This will allow you to POST your transaction String to the endpoint.
I want to fetch data from the rest api of Azure Devops using Java.But not sure how to establish the connection.May be personal acces token will help,but how to use the token in Code for establishing the connection between code and azure devops? An example from anyone will be very helpful.
A code example will be very helpfull
If I am understanding you correctly, you are trying to call azure APIs, and those API need authorization token?
For example this azure API to send data into Azure queue : https://learn.microsoft.com/en-us/rest/api/servicebus/send-message-to-queue
It needs some payload and Authorization in request header !!
If my Understanding is correct, than from java you need to use any rest client or HTTP client to call the REST API and you need to pass the Authorization token in the request header
For calling a Rest API in java with passing header below is an example:
MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
map.add("Authorization", "Bearer <Azure AD JWT token>"); // set your token here
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON); //someother http headers you want to set
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
RestTemplate restTemplate = new RestTemplate();
String azure_url = "https://azure_url"; // your azure devops REST URL
ResponseEntity<String> response = restTemplate.postForEntity(azure_url, request , String.class);
A small example with httpclient:
static String ServiceUrl = "https://dev.azure.com/<your_org>/";
static String TeamProjectName = "your_team_project_name";
static String UrlEndGetWorkItemById = "/_apis/wit/workitems/";
static Integer WorkItemId = 1208;
static String PAT = "your_pat";
String AuthStr = ":" + PAT;
Base64 base64 = new Base64();
String encodedPAT = new String(base64.encode(AuthStr.getBytes()));
URL url = new URL(ServiceUrl + TeamProjectName + UrlEndGetWorkItemById + WorkItemId.toString());
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Authorization", "Basic " + encodedPAT);
con.setRequestMethod("GET");
int status = con.getResponseCode();
Link to the file: ResApiMain.java
You can the use java client library for azure devops rest api. This will take the overload of encoding your personal access token and indeed supports OAuth authentication.
It is been actively developed and used in production.
Source code - https://github.com/hkarthik7/azure-devops-java-sdk
Documentation - https://azure-devops-java-sdk-docs.readthedocs.io/en/latest/?badge=latest
A quick example:
public class Main {
public static void main(String[] args) {
String organisation = "myOrganisationName";
String personalAccessToken = "accessToken";
String projectName = "myProject";
// Connect Azure DevOps API with organisation name and personal access token.
var webApi = new AzDClientApi(organisation, project, personalAccessToken);
// call the respective API with created webApi client connection object;
var core = webApi.getCoreApi();
var wit = webApi.getWorkItemTrackingApi();
try {
// get the list of projects
core.getProjects();
// get a workitem
wit.getWorkItem(15);
// Get a work item and optionally expand the field
wit.getWorkItem(15, WorkItemExpand.ALL);
} catch (AzDException e1) {
e1.printStackTrace();
}
}
}
The library has support to most of the APIs and you can view the documentation and examples folder in the github repo to know how to get the most out of it.
I am a newbie to Solr. I want to use Java to connect to my solr core and get the results back in XML format. By referring the official document, I am able to get the results in binary form. Below is my code:
public static void main(String[] args) throws SolrServerException, IOException {
String urlString = "http://localhost:8983/solr/index1/";
SolrClient solr = new HttpSolrClient.Builder(urlString).build();
SolrQuery query = new SolrQuery();
query.setQuery("*:*");
QueryResponse response = solr.query(query);
System.out.println(response.toString());
}
I also tried to research on how to get response. I found this link which says "If you want to get the raw xml response, just pick up any java HTTP Client, build the request and send it to Solr. You'll get a nice XML String.." solr response in xml format
I coded the below code, but it is not giving me response
public static void main(String[] args) throws ClientProtocolException, IOException
{
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://localhost:8983/solr/index1/select?q=*:*&wt=xml");
CloseableHttpResponse response1 = httpclient.execute(httpGet);
System.out.println(response1);
}
}
Output:
HttpResponseProxy{HTTP/1.1 200 OK [Content-Type: application/xml; charset=UTF-8, Transfer-Encoding: chunked] ResponseEntityProxy{[Content-Type: application/xml; charset=UTF-8,Chunked: true]}}
On the official site https://lucene.apache.org/solr/guide/6_6/using-solrj.html, it is mentioned to use
solr.setParser(new XMLResponseParser());
to get XML response, but I am not sure how to use it since any example is not given. Any help is appreciated.
Edit:
As mentioned in John's comment, I have modified my code as:
System.out.println(EntityUtils.toString(response1.getEntity()));
But in the output, I can see some javascript which is followed by the XML output:
In Solr, the output in XML looks like this:
Not tried but it should work,
You need to initialize org.apache.solr.client.solrj.SolrClient which represents the Solr instance you want to use as follows.
import org.apache.solr.client.solrj.impl.XMLResponseParser;
String serverURL = "http://localhost:8983/solr/<core_name>";
SolrClient solr = new HttpSolrClient.Builder(serverURL).build();
solr.setParser(new XMLResponseParser());
I had an aplication that worked fine with OAuth1 on Mendeley. Since OAth1 is no more supported I have to migrate my app to OAuth2 toget the Data.
I get the token response but I cannot request any content, the program throws a NullPointerException.
I'm testing around with this sourcecode here.
I also use Apache OLTU and the Apache HTTPClient
This is the code I try to run:
static OAuthClientRequest request;
static OAuthClient oAuthClient;
static OAuthJSONAccessTokenResponse tokenResponse ;
static String CATALOG_URL="https://api-oauth2.mendeley.com/oapi/documents/groups?items=10";
request = OAuthClientRequest
.tokenLocation("https://api-oauth2.mendeley.com/oauth/token")
.setClientId(Client_ID)
.setClientSecret(Secret)
.setGrantType(GrantType.CLIENT_CREDENTIALS)
.setScope("all")
.buildBodyMessage();
System.out.println("is set up");
oAuthClient = new OAuthClient(new URLConnectionClient());
tokenResponse = oAuthClient.accessToken( request, OAuthJSONAccessTokenResponse.class);
System.out.println("token is retrieved");
HttpGet httpGet = new HttpGet(CATALOG_URL);
httpGet.setHeader("Authorization", "Bearer " + tokenResponse.getAccessToken());
//this is where the Exception is thrown
HttpResponse httpResponse = apacheHttpClient.execute(httpGet);
//
System.out.println("this is it: "+httpResponse.toString());
String responseAsString = EntityUtils.toString(httpResponse.getEntity());
System.out.println(responseAsString);
The Exception I get is:
Exception in thread "main" java.lang.NullPointerException
I'm now asking myself why this is happening.
The CATALOG_URL is from the Mendeley webside and should return the first Page of the list that contains all public groups.
I also tried different URL from the Mendeley webside.
Could there be anything wrong with the HttpGet statement?
Does anyone have any hints?
You are receiving a NullPointerException because you are using a variable (apacheHttpClient) that has not been initialised. Try doing this first
apacheHttpClient = ApacheHttpTransport.newDefaultHttpClient();
When I make a request to : " https://www.btcturk.com/api/orderbook " via browser or curl I get the response as expected.
When I make the same request via jersey or java libraries such as HttpsURLConnection, I get a 403 forbidden response.
I can use the same methods to make requests to any other urls running under https. An example method can be found below :
public static RestResponse getRestResponse(String url)
{
String jsonString;
try
{
Client client = Client.create();
WebResource webResource = client.resource(url);
ClientResponse response = webResource.accept("application/json")
.get(ClientResponse.class);
if (response.getStatus() != 200) {
return RestResponse.createUnsuccessfulResponse(response.getStatusInfo().getReasonPhrase());
}
jsonString = response.getEntity(String.class);
}
catch(Exception e)
{
return RestResponse.createUnsuccessfulResponse(e);
}
return RestResponse.createSuccessfulResponse(jsonString);
}
The above code is just to give the idea. The whole thing can be found at: https://github.com/cgunduz/btcenter/tree/master/src/main/java/com/cemgunduz/web
My network knowledge is very limited, so any directions towards where I should start would be helpful. Cheers.
You probably have to provide some credentials. Depending on the server configuration you have to provide either a user/password combination or a valid certificate. Try the solutions provided here:
Using HTTPS with REST in Java