JAVA - POST API CALL - java

I'm trying to call an API with basic authorization but without success.
ClientConfig clientConfig = new ClientConfig();
HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("username", "password");
clientConfig.register( feature) ;
clientConfig.register(JacksonFeature.class);
Client client = ClientBuilder.newClient( clientConfig );
String URL = "http://localhost:8080/teste/" + taskId + "/start";
WebTarget webTarget = client.target(URL);
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
Response response = invocationBuilder.get();
System.out.println(response.getStatus());
System.out.println(response.getStatusInfo());
if(response.getStatus() == 200)
{
System.out.println(response.getStatus());
}
I'm getting many errors like:
Could not find a suitable constructor in org.glassfish.jersey.message.internal.SourceProvider$SaxSourceReader class.
java.lang.IllegalArgumentException: Errors were discovered while reifying SystemDescriptor(
Can you help me please?
Some tips?
Greetings

String URL = "http://localhost:8080/teste/" + taskId + "/enable";
HttpPut request = new HttpPut(URL);
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials("user", "password")
);
try (CloseableHttpClient httpClient = HttpClientBuilder.create()
.setDefaultCredentialsProvider(provider)
.build()) {
try (CloseableHttpResponse response = httpClient.execute(request)) {
// 401 if wrong user/password
System.out.println(response.getStatusLine().getStatusCode());
HttpEntity entity = response.getEntity();
if (entity != null) {
// return it as a String
String result = EntityUtils.toString(entity);
System.out.println(result);
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I'm using this solution now and its work, but i need to send a raw body in this request, how i can do that?
Any tip?
Thanks

Related

Java - Sending Message to Slack Webhook

I'm trying to send a message using Slack incoming webhooks. I have the following code. It runs, but when I check my slack, there is no message. Can anyone see what I may have done wrong.
public class SlackTest {
static String web_hook_url = "https://hooks.slack.com/services/***********/******************";
public static void main(String[] args) {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(web_hook_url);
try {
String json = "{\"name\": John}";
System.out.println(json);
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
client.execute(httpPost);
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I first used Postman to test sending the message. Then used Postman to generate the corresponding Java code. Then adjusted the code a bit to arrive at the following . . .
OkHttpClient client2 = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{ \"text\" : \"more text"\" }");
Request request2 = new Request.Builder()
.url("https://hooks.slack.com/services/********/*********/***************")
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "*/*")
.addHeader("Cache-Control", "no-cache")
.addHeader("Host", "hooks.slack.com")
.addHeader("accept-encoding", "gzip, deflate")
.addHeader("Connection", "keep-alive")
.addHeader("cache-control", "no-cache")
.build();
Response response2 = client2.newCall(request2).execute();
This has been working for me today
public void sendByWebHook(String msg) throws SlackApiException {
assert slackMessage != null : "null slackMessage";
final String METHOD_NAME = "sendByWebHook";
final String HOOK_URL = "https://hooks.slack.com/services/T.../B.../FooBar...";
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(HOOK_URL);
try {
String json = "{ \"text\" : \"" + msg + ""\" }";
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
client.execute(httpPost);
client.close();
} catch (UnsupportedEncodingException e) {
logger.error("{}->Error ", METHOD_NAME, e);
throw new SlackApiException("Error sending slack message", e);
} catch (ClientProtocolException e) {
logger.error("{}->Error ", METHOD_NAME, e);
throw new SlackApiException("Error sending slack message", e);
} catch (IOException e) {
logger.error("{}->Error ", METHOD_NAME, e);
throw new SlackApiException("Error sending slack message", e);
}
}

httpclient to upload file results in a corrapted file

I am using apache httpclient to upload a file to a server. I need to use basic authentication(username and password). The response in 200, however, the server logs reveal that the file in missing some data.
public static String pushdata() throws FileNotFoundException, UnsupportedEncodingException {
File file = new File("/home/mohamed/atomtest.txt");
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user", "pass");
provider.setCredentials(AuthScope.ANY, credentials);
HttpClient httpclient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
HttpEntity data = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE).addBinaryBody("file", file).build();
HttpUriRequest request = RequestBuilder.post("link").setEntity(data).build();
ResponseHandler<String> responseHandler = response -> {
int status = response.getStatusLine().getStatusCode();
System.out.println(status);
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
String entityString = EntityUtils.toString(entity);
System.out.println(entityString);
return entityString;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
};
String responseBody = "pushDATA";
try {
responseBody = httpclient.execute(request, responseHandler);
} catch (IOException ex) {
System.out.println(ex.toString());
}
return responseBody;
}
The file is saved as UTF-16, and must be uploaded with the same encoding.
kind regards.

Force.com Apex code counter part or equivalent code to Java

I am not certain if I am on the right path. Since I am not getting any data with the HTTP Request. I needed to convert this java code into force.com apex for me to be able to use a WTS web service.
public static HttpEntity getRequestEntity()
{
JSONArray jsonArr = new JSONArray();
HttpEntity entity = null;
JSONObject jsonElement = new JSONObject();
JSONObject jsonObj = new JSONObject();
JSONObject jsonObj1 = new JSONObject();
jsonElement.put("tenant",jsonObj);
jsonObj.put("companyKey",companyName);
String json = jsonElement.toJSONString();
try {
entity = new StringEntity(json);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return entity;
}
private static void GetEnabledUsers(String responseContent) throws ParseException, ClientProtocolException, IOException {
String url = "<endpoint>/services/UserService1.svc/GetEnabledUsers";
// Create an http client to perform the http communication
CloseableHttpClient httpClient = HttpClients.createDefault();
// Http request to specific web service. Request will be given to client
HttpPost request = new HttpPost(url);
// Create credentials for the authentication
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credential = new UsernamePasswordCredentials(companyName+'\\'+userName, password);
provider.setCredentials(AuthScope.ANY, credential);
HttpClientContext localContext = HttpClientContext.create();
localContext.setCredentialsProvider(provider);
// Make the actual http request
HttpPost httpRequest = new HttpPost(url);
HttpEntity requestEntity = getRequestEntity();
if(requestEntity != null) {
httpRequest.setHeader("Content-type", "application/json");
httpRequest.setEntity(requestEntity);
}
CloseableHttpResponse response = httpClient.execute(httpRequest, localContext);
HttpEntity entity = response.getEntity();
String responseContent1 = EntityUtils.toString(entity);
System.out.println(responseContent1);
}
This is what I have so far:
String userName= '<userName>';
String password= '<password>';
String companeyKey = '<companeyKey>';
JSONGenerator jsonGenerator = JSON.createGenerator(true);
jsonGenerator.writeStartObject();
jsonGenerator.writeFieldName('tenant');
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField('companeyKey', '<companeyKey>');
jsonGenerator.writeEndObject();
jsonGenerator.writeEndObject();
requestBody = jsonGenerator.getAsString();
Blob headerValue = Blob.valueOf(userName + ':' + password);
HttpRequest requestEntity = new HttpRequest();
String authHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
requestEntity.setMethod('POST');
requestEntity.setEndPoint('<endpoint>/services/UserService1.svc/GetEnabledUsers');
requestEntity.setHeader('Content-Type', 'application/json');
requestEntity.setHeader('Authorization', authHeader);
requestEntity.setBody(requestBody);
Http http = new Http();
HTTPResponse responseEntity = http.send(requestEntity);
system.debug(responseEntity);
On difference seems to be around how the username is constructed for the auth parameter, change
Blob headerValue = Blob.valueOf(userName + ':' + password);
to
Blob headerValue = Blob.valueOf(companyKey + '\\' + userName + ':' + password);

Rest Method throwing exception when static

I am trying to RestApi call , The below code i had worked before it wasn't a static method and now that it is a static method it is throwing this exception below: When it is in the same class, it works.
Cause:java.io.EOFException: SSL peer shut down incorrectly
DetailMessage: Remote host closed connection during handshake
public static void getMethod(String pass,String query,String url)throws Exception{
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials("fzs", pass));
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).setProxy(new HttpHost("proxyName",80))
.build();
try {
String encode = url + (URLEncoder.encode(query,"UTF-8"));
HttpUriRequest httpget = new HttpGet(encode);
System.out.println("Executings request " + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
String message = EntityUtils.toString(entity);
EntityUtils.consume(entity);
System.out.println(message);
} finally {
response.close();
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
finally {
httpclient.close();
}
}
Working code:
#Test
public void RestAPI() throws Exception {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials("fzs", pass));
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).setProxy(new HttpHost("proxyName",80))
.build();
try {
String query = "active=true^state!=3^u_entity=u_case^GOTOnumber=CASE0014474";
String url = "https://service-now.com/api/now/table/u_case?sysparm_query=";
String encode = url + (URLEncoder.encode(query,"UTF-8"));
HttpUriRequest httpget = new HttpGet(encode);
System.out.println("Executings request " + httpget.getRequestLine());
// ResponseHandler<String> responseHandler=new BasicResponseHandler();
// String responseBody = httpclient.execute(httpget, responseHandler);
CloseableHttpResponse response = httpclient.execute(httpget);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
EntityUtils.consume(response.getEntity());
// System.out.println(responseBody);
} finally {
response.close();
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
finally {
httpclient.close();
}
}

Android Unable to Retrieve JSON response [SC_406]

I have the code which basically retrieving a list of search result based on given keyword from TMDB (API ver.3, new API).
public String getPersonSearchResult(String keywords){
String query = URLEncoder.encode(keywords);
String TMDB_API_URL = "http://api.themoviedb.org/3/search/person?";
String TMDB_LIMIT_LIST = "&page=1";
String TMDB_QUERY = "&query=" + query;
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try
{
// ATTEMPT HTTP REQUEST
String fullUrl = TMDB_API_URL + TMDB_API_KEY + TMDB_QUERY + TMDB_LIMIT_LIST;
Log.w(APP_TAG, "TRYING [" + fullUrl + "]");
response = httpclient.execute(new HttpGet(fullUrl));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK)
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
}else{
// FAILED REQUEST - CLOSE THE CONNECTION
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
}catch(Exception e){
Log.w(APP_TAG, e.getLocalizedMessage());
Log.w(APP_TAG, "FAILED TO RETRIEVE JSON DATA");
}
return responseString;
}
The problem is that i always get 406 Status Code (Not Acceptable). When i tried to run the URL myself
http://api.themoviedb.org/3/search/person?api_key=<MY_API_KEY_HERE>&query=jennifer&page=1
It displays the JSON result correctly.
I am not sure why is this happening. Similar function is used to retrieve JSON value from other source and and it works perfectly.
this is their API docs regarding search: http://docs.themoviedb.apiary.io/#search
Can anyone points me to the right direction? Any help is appreciated.
I figure it out, by adding this:
HttpGet getObj = new HttpGet(fullUrl);
getObj.addHeader("Accept", "application/json");
Perhaps this is API specific requirement. Not sure though...
One way to do it
Try using builder.scheme
URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("api.themoviedb.org").setPath("/3/search/person")
.setParameter("api_key", YOURAPIKEY)
.setParameter("page", 1)
.setParameter("query", query)
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
.....
response = httpclient.execute(new HttpGet(httpget ));
I think its nothing to do with your code.. your code is perfect. The only problem might be with the API request method. Maybe they require some specific headers to be requested for in the request. Give a try with requesting headers like "("Accept", "application/json")" It might work..
try this
String ret = null; try {
response = httpClient.execute(httpGet);
} catch (Exception e) {
e.printStackTrace();
}
try {
ret = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
Log.e("HttpRequest", "" + e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
return ret;

Categories

Resources