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();
}
}
Related
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
if face problem just in Godaddy server when executing google API the request return connection time out,
only this request.
but on my other servers (digital ocean and local server), it runs and everything is well and same code and the same configuration
String dataSTR = data.toString();
HttpPost request = new HttpPost("https://fcm.googleapis.com/fcm/send");
StringEntity params = new StringEntity(dataSTR, "UTF-8");
String key = "key=" + authKey;
request.addHeader("Authorization", key);
request.addHeader("content-type", "application/json");
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.addHeader("content-type", "charset=UTF-8");
request.setEntity(params);
System.out.println(request);
System.out.println("______");
HttpResponse response;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
System.out.println(responseString);
System.out.println(response);
} catch (ClientProtocolException e) {
LOGGER.error(e.getMessage(), e);
return false;
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
return false;
}
I have the following code using try with resources with CloseableHttpResponse
CloseableHttpResponse response = null;
try (CloseableHttpClient httpClient = HttpClients.custom().build()){
//code...
response = httpClient.execute(target, post);
String responseText = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
logger.error("Failed sending request", e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
logger.error("Failed releasing response", e);
}
}
}
Can I safely replace with nested try with resources:
try (CloseableHttpClient httpClient = HttpClients.custom().build()){
URIBuilder uriBuilder = new URIBuilder(url);
HttpHost target = new HttpHost(uriBuilder.getHost(), uriBuilder.getPort(), uriBuilder.getScheme());
HttpPost post = new HttpPost(uriBuilder.build());
try (CloseableHttpResponse response = httpClient.execute(target, post)) {
String responseText = EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
logger.error("Failed sending request", e);
}
Or is it better to use a single try with resources block:
try (CloseableHttpClient httpClient = HttpClients.custom().build();
CloseableHttpResponse response = getResponse(httpClient, url)) {
Sometime refactoring to single block is problematic, so I wanted to know the a nested/additional block is a valid solution.
HttpClient never returns a null HttpResponse object. The first construct is simply not useful. Both the second and the third constructs are perfectly valid
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.
I try upload some string to server. When I try upload on server, in string:
HttpResponse response = httpclient.execute(httppost);
I have error org.apache.http.client.ClientProtocolException. All code:
public void sendString(String stringToSend) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
HttpPost httppost = new HttpPost(serverAddress);
InputStreamEntity reqEntity = new InputStreamEntity( new ByteArrayInputStream(stringToSend.getBytes()), stringToSend.length());
reqEntity.setContentType("application/xml");
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != org.apache.http.HttpStatus.SC_OK) {
Log.i("SEND", "not send "+response.getStatusLine());
}else{
Log.i("SEND", "send ok "+response.getStatusLine());
}
} catch (IOException e) {
Log.w("IOException", e.toString() +" "+ e.getMessage());
}
}
This should work
public void sendString(String stringToSend) {
try {
HttpParams httpParams=new BasicHttpParams();
DefaultHttpClient httpclient = new DefaultHttpClient(httpParams);
httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
HttpPost httppost = new HttpPost(serverAddress);
InputStreamEntity reqEntity = new InputStreamEntity( new ByteArrayInputStream(stringToSend.getBytes()), stringToSend.length());
reqEntity.setContentType("application/xml");
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != org.apache.http.HttpStatus.SC_OK) {
Log.i("SEND", "not send "+response.getStatusLine());
}else{
Log.i("SEND", "send ok "+response.getStatusLine());
}
} catch (IOException e) {
Log.w("IOException", e.toString() +" "+ e.getMessage());
}
}