Hiding the logs of an API call - java

I am making an http request using Httpclient and I need to hide logs for this specific API call as it contains sensitive data. We need the logs to be in debug level so lowering the log level is not an option is there a way that I can hide the logs of just this request?
public Boolean authenticate(String userName, String password) throws IOException {
HttpPost httpPost = new HttpPost(authServiceBaseUrl + AUTH_SERVICE_AUTH_URI);
try {
StringEntity httpEntity = new StringEntity(new JSONObject()
.put(USERNAME_ATTRIBUTE_NAME, userName)
.put(PASSWORD_ATTRIBUTE_NAME, password)
.toString());
httpEntity.setContentType(ContentType.APPLICATION_JSON.toString());
httpPost.setEntity(httpEntity);
} catch (Exception e) {
throw new Exception(logException(userName, "authenticate"), e );
}
try (CloseableHttpClient httpClient = getHttpClient();
CloseableHttpResponse response = httpClient.execute(httpPost)) {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return Boolean.TRUE;
} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
log.warnf("[%s] Authentication failed.", userName);
return Boolean.FALSE;
} else {
throw new UserAuthenticationException(
response.getStatusLine().getStatusCode(), userName,
"Error while trying to authenticate user");
}
} catch (UserAuthenticationException e) {
throw e;
} catch (Exception e) {
throw new Exception(logException(userName, "authenticate"), e);
}
}

Related

How to get response in Map in httpClient?

I'm making a request to my server, but the response is given in String, and I need to get data from there, for example, the if response: {"response":{"balance":85976,"adres":"pasaharpsuk#gmail.com"}}
and need to get a balance
CODE:
public class test {
public static void main(String[] args) {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// Создать запрос на получение
HttpGet httpGet = new HttpGet("http://localhost:8080/api/bank/my_wallet");
httpGet.setHeader("Authorization", "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJwYXNhaGFycHN1a0BnbWFpbC5jb20iLCJyb2xlIjoiVVNFUiIsImlhdCI6MTY1MjUzNzQ3NSwiZXhwIjoxNjUzNTM3NDc1fQ.zYQqgXA0aeZAMm7JGhv4gOQEtks2iyQqGoqOOrdxy5g");
// модель ответа
CloseableHttpResponse response = null;
try {
// Выполнить (отправить) запрос Get от клиента
response = httpClient.execute(httpGet);
// Получить объект ответа из модели ответа
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
System.out.println(EntityUtils.toString(responseEntity));
}
} catch (ParseException | IOException e) {
e.printStackTrace();
} finally {
try {
// освободить ресурсы
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
'''
All you need is a JSON parser for the entity after checking the content type header. https://hc.apache.org/httpcomponents-core-4.4.x/current/httpcore/apidocs/org/apache/http/HttpEntity.html#getContentType()
For example you can use JSONObject from org.json to convert string to json. https://developer.android.com/reference/org/json/JSONObject#JSONObject(java.lang.String)
JSONObject o = new JSONObject(EntityUtils.toString(responseEntity));

Move CloseableHttpResponse inside nested try with resources

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

where is the wrong in this syntax of calling http request get

I have this call (from the browser)
http://serverName:8081/cmp-mg-?sub_x?=7
and it returns 200 response
and I want to call do that request from my web service:
this is my web service:
public Response sendMT2(#BeanParam MT mt) throws IOException {
try {
HttpHost host = new HttpHost("serverName", 8081);
HttpClient client = HttpClientBuilder.create().build();
HttpRequest request = new BasicHttpRequest("GET",
"/serverp/sam?" + mt.getURLParameter());
System.out.println("/cmp-mg-xconn-http-webapp/sam?"
+ mt.getURLParameter());
HttpResponse response = client.execute(host, request);
String responseString = new BasicResponseHandler()
.handleResponse(response);
return Response.ok(responseString).build();
} catch (ClientProtocolException e) {
throw e;
// return Response.status(500).build();
} catch (IOException e) {
throw e;
// return Response.status(500).build();
}
}
but I am getting error
org.apache.http.client.HttpResponseException: Not Found
what is the wrong?
I found the error myself.
before sub-r_mob .. i had ? instead of &

GCM send message from one device to other without any third part server

I am trying to send messages from device to device, without the use of any third part server(Well I do use it for some other parts).
I am using HTTP request to send it to gcm server directly from device.
Heres what I have done.
try {
HttpPost httppost;
try {
httppost = new HttpPost(
"https://android.googleapis.com/gcm/send");
} catch (IllegalArgumentException e) {
e.printStackTrace();
return false;
}
httppost.setHeader("Authorization", "key=512218918480");
httppost.setHeader("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
ArrayList<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("registration_id", id));
postParams.add(new BasicNameValuePair("data.mode",
"exampleContentOfYourMessage"));
postParams.add(new BasicNameValuePair("m",
"exampleContentOfYourMessage"));
HttpResponse response;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity entity;
try {
httppost.setEntity(new UrlEncodedFormEntity(postParams, "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return false;
}
try {
response = httpClient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
entity = response.getEntity();
if (entity != null
&& response.getStatusLine().getStatusCode() == 200) {
return true;
} else {
Log.e("Tag", "No Connection");
return false;
}
} catch (Exception e) {
Log.e("grokkingandroid",
"IOException while sending registration id", e);
}
return false;
}
This returns
02-24 00:19:13.772: W/DefaultRequestDirector(9913): Authentication error: Unable to respond to any of these challenges: {}
So it looks like authentication error for https . DO I need to send something more to gcm server?
I also know the flaws for using this method.My id would be in app so less security.I cant send much data and so on.

NetworkOnMainThreadException sometimes thrown

I try to get response from POST request. The problem is that sometimes I get NetworkOnMainThreadException although I'm using AsyncTask for the network communication. That means that sometimes I get the response successfully, and sometimes I get this exception.
Here is my HTTP POST request AsyncTask:
static class HTTPPostRequest extends AsyncTask<PostRequestParams, Void, AsyncResponse> {
#Override
protected AsyncResponse doInBackground(PostRequestParams... params) {
AsyncResponse retVal = new AsyncResponse();
HttpClient client = getHttpClient();
UrlEncodedFormEntity formEntity = null;
HttpPost request = new HttpPost();
try {
request.setURI(new URI(params[0].URL));
formEntity = new UrlEncodedFormEntity(params[0].params);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
retVal.setOutput(response);
} catch (ClientProtocolException e) {
retVal.setException(e);
} catch (IOException e) {
retVal.setException(e);
} catch (URISyntaxException e) {
retVal.setException(e);
}
return retVal;
}
}
And the code that actually call it:
AsyncResponse response = new AsyncResponse();
PostRequestParams postParams = new PostRequestParams();
postParams.URL = URL + "login.php";
postParams.params.add(new BasicNameValuePair("username", username));
postParams.params.add(new BasicNameValuePair("password", password));
try {
response = new HTTPPostRequest().execute(postParams).get();
if (response.getException() != null) {
return "Error";
}
HttpResponse httpResponse = (HttpResponse) response.getOutput();
if (httpResponse.getStatusLine().getStatusCode() != 200) {
return "Error " + httpResponse.getStatusLine().getStatusCode();
}
return (String) formatResponse(new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())));
} catch (InterruptedException | ExecutionException | IllegalStateException | IOException e) {
response.setException(e);
return null;
}
You should move the code that handles the InputStream, like:
return (String) formatResponse(new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())));
to your AsyncTask as well. Handling InputStreams is nothing that you want to do in your UI Thread.

Categories

Resources