httpclient post basic authentication - spring

Is there an easier way to setup the http client for preemptive basic authentication than what described.
I have to post from my spring boot service to another external service, but this is not possible in my attempt.
What a mistake I made in doing this.
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1", "user1Pass");
provider.setCredentials(AuthScope.ANY, credentials);
HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
HttpPost httpPost = new HttpPost("http://91.204.239.42:8083/broker-api/send");
httpPost.setHeader("Content-type", "application/json");
try {
httpPost.setEntity(new StringEntity(json));
HttpResponse response = client.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
return statusCode;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 500;
this stacktrace
org.apache.http.conn.HttpHostConnectException: Connect to 91.204.239.42:8083 [/91.204.239.42] failed: Connection refused: connect
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:156) ~[httpclient-4.5.9.jar:4.5.9]
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:374) ~[httpclient-4.5.9.jar:4.5.9]

I tried many methods but to no avail. Then I decided to contact the api manufacturer and they would tell me that this api only works if we allow it. He started working when he got permission. The cause of the problem is permissions

Related

Jetty httpclient add proxy socks4

When i'm trying to send request via jetty httpClient with new Socks4Proxy(socksHost, socksPort); received: java.util.concurrent.ExecutionException: java.io.IOException: SOCKS4 tunnel failed with code 91
HttpClient httpClient = new HttpClient();
ProxyConfiguration proxyConfig = httpClient.getProxyConfiguration();
Socks4Proxy proxy = new Socks4Proxy(socksHost, socksPort);
proxyConfig.getProxies().add(proxy);
httpClient.start();
String url = config.getProperty(stringUrl);
Request request = httpClient.newRequest(url);
request.method(HttpMethod.GET);
request.onResponseContent(new BufferingResponseListener() {
#Override
public void onComplete(Result result) {
String s = getContentAsString();
logger.debug("Received http response message: '{}', status: '{}'", s, result.getResponse().getReason());
}
});
try {
request.send();
} catch (Exception e) {
throw new RuntimeException(e);
}
Per https://www.openssh.com/txt/socks4.protocol
Your 91 status means that request was rejected or failed. The user or source program is not authorized to access the proxy server.
Perhaps your SOCKS4 proxy has an authentication requirement.

Spring RestTemplate Connection Timeout

Any help or hint would be greatly appreciated it.
I tried the below RestTemplate code in Eclipse and Intellij and I get the same connection timeout error. If I run it on a browser I am able to connect.
enter image description here
org.springframework.web.client.ResourceAccessException: I/O error on GET request for "https://registry-relationship-dev.api.non-prod-uw2.hponecloud.io/ocrel-registry/v2/node/sub.node.0025s": Connection timed out: connect; nested exception is java.net.ConnectException: Connection timed out: connect
try {
String tempUrl = registryUrl;
if (roleInput.getNodeId() != null) {
tempUrl = tempUrl + roleInput.getNodeId();
}
URI uri = new URI(tempUrl);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization",auth);
headers.set("Content-Type","application/json");
HttpEntity<String> entity = new HttpEntity<String>("parameters",headers);
RestTemplate restTemplate = new RestTemplate();
// ResponseEntity<String> response = restTemplate.exchange(tempUrl,HttpMethod.GET, entity,String.class);
ResponseEntity<NodeModel> response1 = restTemplate.exchange(tempUrl,HttpMethod.GET, entity,NodeModel.class);
NodeModel response = restTemplate.getForObject("https://registry-relationship-dev.api.non-prod-uw2.hponecloud.io/ocrel-registry/v2/node/sub.node.0025s",NodeModel.class);
System.out.println("response from registry:"+response);
}
log.info("createRole,After call authLibService.validateToken(auth):"+auth);
} catch (Exception e) {
log.error("Failed to check permission, createRole getMessage error: {}", e.getMessage());
log.error("Failed to check permission, createRole getStackTrace error: {}", e.getStackTrace());
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}

Migrating from Jersey client to RestTemplate, but it catch 401 error as HttpClientErrorException but Jersey client was not throwing this error why?

In my Service there was Jersey client implementation to call a rest API now I was migrating this code to RestTemplate.
In old code when there was a 401 error that comes as a response from the backend and I store the response in an object.
But when I migrated the code to RestTeplate the 401 is caught by HttpClientErrorException class so I am not able to get the response since the code flow goes to the catch block.
Jersey Client code
public Employees getEmployees1() throws MyException {
Employee employee=new Employee(23, "Test", "Test", "Test#test.com");
ClientResponse response=null;
try {
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/employees/");
response = webResource.accept("application/json")
.type("application/json").header("Authorization", "invalid Data").post(ClientResponse.class, employee);
}catch (RuntimeException e) {
logger.error("Runtime Error Occured -{} Response - {} ",e.getMessage(),response.getStatus());
throw new MyException("Unexpected Error Occured",e);
}catch (Exception e) {
logger.error("Some Error Occured -{} Response - {} ",e.getMessage(),response.getStatus());
throw new MyException("Unexpected Error Occured",e);
}
return response.readEntity(Employees.class);
}
RestTemplate Code
public Employees getEmployees() throws MyException {
Employee employee=new Employee(23, "Test", "Test", "Test#test.com");
HttpHeaders headers=new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.add(HttpHeaders.AUTHORIZATION, "invalid Data");
ResponseEntity<Employees> response=null;
try {
response = this.restTemplate.exchange("http://localhost:8080/employees/", HttpMethod.POST, new HttpEntity<Employee>(employee,headers), Employees.class);
}catch (RuntimeException e) {
logger.error("Runtime Error Occured -{} Response - {} ",e.getMessage(),response.getStatusCode());
throw new MyException("Unexpected Error Occured",e);
}catch (Exception e) {
logger.error("Some Error Occured -{} Response - {} ",e.getMessage(),response.getStatusCode());
throw new MyException("Unexpected Error Occured",e);
}
return response.getBody();
}
By default RestTemplate throws an HttpStatusCodeException (a child of it) for all 400+ status codes - see DefaultResponseErrorHandler. You can change this behavior by setting your own implementation of ResponseErrorHandler to RestTemplate using setErrorHandler or if RestTemplate is constructed using RestTemplateBuilder - using errorHandler method of the builder.
I used the default ResponseErrorHandler, by using this it will bypass all the ResponseError exception
RestTemplate rt = restTemplateBuilder.errorHandler(new ResponseErrorHandler(){
#Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return false;
}
#Override
public void handleError(ClientHttpResponse response) throws IOException {
}})
.build();

How to handle the http response from an api call efficiently using spring boot

When we fire an api call to a 3rd party service, we can get different HTTP responses (200, 404 etc.). How can we handle them in a standard way?
private ResponseEntity<ResultHolder> responseEntity;
public ResponseEntity<ResultHolder> serviceTest(String searchText, String countryCode) {
logger.info("Service started");
String url = prepareUrl(searchText,countryCode); //custom method
HttpHeaders header = new HttpHeaders();
prepareHeader(header); //custom method
HttpEntity<String> requestEntity = new HttpEntity<String>(header);
try {
logger.info("Calling the API");
responseEntity = restClient.exchange(url,
HttpMethod.GET,
requestEntity,
ResultHolder.class);
}catch (Exception e) {
logger.error("Exception while calling the API "+ e);
//Here I am trying to get the value of response code and handle based on that
//Is this the right way to solve the problem?
if(responseEntity.getStatusCodeValue() != 200) {
responseEntity = new ResponseEntity<ResultHolder>(
HttpStatus.BAD_REQUEST);
}
}
logger.info("Service Ended");
return responseEntity;
}
What if I want to display distinct custom messages for server side errors and for user errors like 'No Internet Connection'.
Kindly help me to understand the good practises in this area.
Thank you

sending email from spring app using godaddy

Hi i'm trying to send mail from my spring boot app using godaddy email.
I have purchase the domain name and email id .Now i want to send mail from that domain, but it showing some errors.
public boolean sendMail(String to, String subject, String content) {
String from = "info#mydomain.com";
String password ="***********";
try {
Properties props = System.getProperties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtpout.mydomain.com");
props.put("mail.smtp.starttls.enable","true" );
props.put("mail.smtp.auth", "true");
props.setProperty("mail.user", from);
props.setProperty("mail.password", password);
Session mailSession = Session.getDefaultInstance(props);
// mailSession.setDebug(true);
Transport transport = mailSession.getTransport("smtp");
MimeMessage message = new MimeMessage(mailSession);
message.setSentDate(new java.util.Date());
message.setSubject(subject);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setContent(content, "text/html");
transport.connect("smtpout.mydomain.com",from,password);
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
Errors:
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtpout.mydomain.com, 25; timeout -1;
nested exception is:
java.net.ConnectException: Connection refused: connect

Resources