HttpRequestBase - How to print the request with all its data - java

I'm using HttpRequestBase and I want to log the request fully to a log file before using it.
The default toString returns only the request line and I want to print all the headers, parameters, request body etc...
Is there a way to do so?

The HttpRequestBase object (HttpGet, HttpPost, etc.) contains information about the headers, parameters, and the implementation class contains the body, but it's not actually serialized into a String. That happens when the HttpClient actually sends the request.
You can play with the http components logging configuration.
Or you can call the appropriate methods and do it yourself.
HttpRequestBase base = new HttpGet("www.google.com");
Header[] headers = base.getAllHeaders();
// iterate and print
For the body, you need to cast to your implementation class and get the HttpEntity, if it has one.
HttpEntity entity = ((HttpPost)base).getEntity(); // example
And print it (its InputStream content). Note: That might consume the entity.
Full example
HttpPost post = new HttpPost("www.google.com");
post.setHeader(new BasicHeader("User-Agent", "random client"));
HttpEntity entity = new StringEntity("yellaworld");
post.setEntity(entity);
Header[] headers = post.getAllHeaders();
String content = EntityUtils.toString(entity);
System.out.println(post.toString());
for (Header header : headers) {
System.out.println(header.getName() + ": " + header.getValue());
}
System.out.println();
System.out.println(content);
prints
POST www.google.com HTTP/1.1
User-Agent: random client
yellaworld

This works
private void printRequest() {
System.out.println("receive " + httpRequest.getMethod() +" notification for "+ httpRequest.getRequestURI());
System.out.println(" \n\n Headers");
Enumeration headerNames = httpRequest.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = (String)headerNames.nextElement();
System.out.println(headerName + " = " + httpRequest.getHeader(headerName));
}
System.out.println("\n\nParameters");
Enumeration params = httpRequest.getParameterNames();
while(params.hasMoreElements()){
String paramName = (String)params.nextElement();
System.out.println(paramName + " = " + httpRequest.getParameter(paramName));
}
System.out.println("\n\n Row data");
System.out.println(extractPostRequestBody(httpRequest));
}
static String extractPostRequestBody(HttpServletRequest request) {
if ("POST".equalsIgnoreCase(request.getMethod())) {
Scanner s = null;
try {
s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A");
} catch (IOException e) {
e.printStackTrace();
}
return s.hasNext() ? s.next() : "";
}
return "";
}

Related

i was given task to fix sonar issues and generate report, then there is an error "Use a more secure method than basic authentication", couldn't get it

would appreciate any help to fix it with some detailed explanation , one of the solution saying to use Digest authentication, if it's correct, how do we use in the below code, the error pointed to "httppost.setHeader("Authorization", "Basic " + encoding);" this line
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
String encoding;
LOGGER.info("Entered into try");
if (direction != null && direction.equalsIgnoreCase(ASPERA_DIRECTION_DOWNLOAD)) {
LOGGER.info("entered if");
url = acceleratorUtilConfig.getAccelDownloadSetupUrl();
path = acceleratorUtilConfig.getS3DownloadRootPath() + path;
encoding = new String(Base64.encodeBase64((acceleratorUtilConfig.getAccelDownloadAccessKey() + ":" + acceleratorUtilConfig.getAccelDownloadSecret()).getBytes()));
} else {
LOGGER.info("entered else");
url = acceleratorUtilConfig.getAccelUploadSetupUrl();
path = acceleratorUtilConfig.getS3UploadRootPath() + path;
encoding = new String(Base64.encodeBase64((acceleratorUtilConfig.getAccelUploadAccessKey() + ":" + acceleratorUtilConfig.getAccelUploadSecret()).getBytes()));
}
LOGGER.debug("GenerateToken : {} : {}", url, path);
LOGGER.debug(": {}", encoding);
LOGGER.debug(" : {} : {}", direction, filePathArray);
LOGGER.debug("NewGenerateToken : {}", acceleratorUtilConfig.getAccelDownloadSetupUrl());
TokenRequest tokreq = new TokenRequest(
Stream.of(new TransferRequest(new TransferRequestAttribute(true, "always", direction, path,
pathModel.getPathList(filePathArray), null), null)).collect(Collectors.toList()),
null);
ObjectMapper mapper = new ObjectMapper();
String inJson = "";
inJson = mapper.writeValueAsString(tokreq);
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Authorization", "Basic " + encoding);
StringEntity input = new StringEntity(inJson);
httppost.setEntity(input);
LOGGER.debug("GenerateToken : Request sent");
HttpResponse response1 = httpClient.execute(httppost);
LOGGER.debug("GenerateToken : response returned");

User object cannot be resolved to a variable

Am novice. Just wrote down a function for login that returns User object but am getting error in last line return oUser as "oUser cannot be resolved to a variable". Can someone please help me in it.I am using User as the return type for sLoginContractTest function.
public User sLoginContractTest(String sUserName, String sPassword, String sDomain,
String sBusUnitID) throws Exception {
String[] sInfo = new String[2];
Gson gson = new GsonBuilder().create();
// Create your http client
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
// Create http post object
// HttpPost postRequest = new HttpPost(sUrl);
HttpPut putRequest = new HttpPut(this.sAuthUrl);
// Message Body
StringEntity input = new StringEntity("{\"userId\":\"" + sUserName
+ "\",\"password\":\"" + sPassword + "\",\"businessUnitId\":\""
+ sBusUnitID + "\",\"domainName\":\"" + sDomain + "\"}");
// Set content type for post
input.setContentType("application/json");
// attach message body to request
putRequest.setEntity(input);
// submit request and save response
HttpResponse response = httpclient.execute(putRequest);
// get status code from response
int sStatusCode = response.getStatusLine().getStatusCode();
// Check if status code returned is 200 (success) or other (failure)
if (sStatusCode != 200) {
ReportResults("FAIL", "Login Failed due to " + response.toString(),
false);
Assert.fail(response.getStatusLine().getReasonPhrase());
sInfo = null;
}
// Expected response
else if (sStatusCode == 200) {
System.out.println(response.toString());
ReportResults("PASS", "Logged in Successfully.", false);
// Get response body (entity and parse to string
String sEntity = EntityUtils.toString(response.getEntity());
User oUser = gson.fromJson(sEntity, User.class);
// Get securityID and token
sInfo[0] = this.getJsonResponseValue(sEntity, "securityId");
sInfo[1] = this.getJsonResponseValue(sEntity, "token");
//Check to see if Contract is valid
try{
if(oUser!=null){
return oUser;
}
else{
return null;
}
}
catch(Exception e){
//If exception, contract failed (might want to check for specific exception here)
ReportResults("FAIL", "Login user contract failed because: " + e.getMessage(),false);
}
this.setUserID(sUserName);
this.sAuthToken = sInfo;
System.out.println("the security id is" + this.sAuthToken[0]);
System.out.println("the token id is " + this.sAuthToken[1]);
}
return oUser;
}

How to use httpclient 4.3.6 to invoke DCTM 7.1 REST API?

I am looking to interact with a Documentum Repository using their REST API. I would like to use the http-client 4.3 jars to perform this interaction.
I was hoping someone might have a sample that would help point me in the correct direction on how to interact with DCTM.
I am having trouble finding a clear and simple example of how to do this.
Thanks
I know it is a bit late to answer this question. But i want to answer to help those who still need a code for making requests to the rest api. Here is a full example of sending a post request to the rest api for starting a workflow.
For other needs you can check the Document called Documentum xCP Rest Services provided by EMC : https://support.emc.com/docu52500_Documentum-xCP-REST-Services-2.1-Development-Guide.pdf?language=en_US&request=akamai and compare with this example, change it according to it's needs.
UPDATE:
Also if you are not using xcp here is the Documentation for rest api without it emc.com/collateral/TechnicalDocument/docu57895.pdf
You can also check my answer here How can I use REST to copy an object in Documentum 7.x for geting object data and content from the rest api ( without xcp )
String strResponse = "";
String process_id = "system_name of the process you want to start";
String url = "Your App Url Here/processes/" + process_id;
String json = "{"+
"\"run-stateless\" : \"false\","+
"\"data\" :"+
" { "+
" \"variables\" : "+
" { \"Variable name\" : \"Variable value\" } "+
" } "+
"}";
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
BufferedReader rd = null;
CloseableHttpResponse cls = null;
try {
HttpPost request = new HttpPost(url);
// set timeouts as you like
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(60 * 1000).setConnectTimeout(20 * 1000)
.setConnectionRequestTimeout(20 * 1000).build();
request.setConfig(config);
StringEntity params = new StringEntity(json);
request.addHeader("Accept", "application/json");
request.addHeader(
"Authorization",
"Basic "
+ com.documentum.xmlconfig.util.Base64
.encode("username here" + ":"
+ "password here"));
request.addHeader("Content-Type", "application/vnd.emc.xcp+json");
request.setEntity(params);
try {
cls = httpClient.execute(request);
HttpEntity entity = cls.getEntity();
rd = new BufferedReader(new InputStreamReader(
entity.getContent()));
String line = "";
while (line != null) {
line = rd.readLine();
strResponse += line;
}
strResponse = strResponse.trim().replace("\n", "");
String statusline = cls.getStatusLine().toString();
if (!statusline.contains("200") && !statusline.contains("201")) {
Log.write("Process is not started");
// log the strResponse or do something with it
} else {
System.out.println("Process started successfully");
}
} catch (Exception e) {
e.printStackTrace();
}
} finally {
// using commons-io-2.4.jar
IOUtils.closeQuietly(httpClient);
IOUtils.closeQuietly(cls);
IOUtils.closeQuietly(rd);
}

Java: Adding raw data to payload Httpost request

I intend to send a simple http post request with a large string in the Payload.
So far I have the following.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("address location");
String cred = "un:pw";
byte[] authEncBytes = Base64.encodeBase64(cred.getBytes());
String authStringEnc = new String(authEncBytes);
httppost.setHeader("Authorization","Basic " + authStringEnc);
However, I do not know how to attach a simple RAW string into the payload. The only examples I can find are name value pairs into the Entity but this is not what I want.
Any assistance?
It depends on the concrete HTTP-API you're using:
Commons HttpClient (old - end of life)
Since HttpClient 3.0 you can specify a RequestEntity for your PostMethod:
httpPost.setRequestEntity(new StringRequestEntity(stringData));
Implementations of RequestEntity for binary data are ByteArrayRequestEntity for byte[], FileRequestEntity which reads the data from a file (since 3.1) and InputStreamRequestEntity, which can read from any input stream.
Before 3.0 you can directly set a String or an InputStream, e.g. a ByteArrayInputStream, as request body:
httpPost.setRequestBody(stringData);
or
httpPost.setRequestBody(new ByteArrayInputStream(byteArray));
This methods are deprecated now.
HTTP components (new)
If you use the newer HTTP components API, the method, class and interface names changed a little bit, but the concept is the same:
httpPost.setEntity(new StringEntity(stringData));
Other Entity implementations: ByteArrayEntity, InputStreamEntity, FileEntity, ...
i was making a common mistake sequence of json object was wrong. for example i was sending it like first_name,email..etc..where as correct sequence was email,first_name
my code
boolean result = false;
HttpClient hc = new DefaultHttpClient();
String message;
HttpPost p = new HttpPost(url);
JSONObject object = new JSONObject();
try {
object.put("updates", updates);
object.put("mobile", mobile);
object.put("last_name", lastname);
object.put("first_name", firstname);
object.put("email", email);
} catch (Exception ex) {
}
try {
message = object.toString();
p.setEntity(new StringEntity(message, "UTF8"));
p.setHeader("Content-type", "application/json");
HttpResponse resp = hc.execute(p);
if (resp != null) {
if (resp.getStatusLine().getStatusCode() == 204)
result = true;
}
Log.d("Status line", "" + resp.getStatusLine().getStatusCode());
} catch (Exception e) {
e.printStackTrace();
}
return result;
Answer

HTTPClient StringEntity PUT troubles

I am struggling with creating a plain text file on a server via HTTP PUT. I am using apache commons httpClient. My credentials are working but there is no body content in my request. What must I do to create the file like this? It works as intended when I try via hurl.it (ie setting my credentials, and setting a body). What I would like is the string "hej" to show in the file body. After getting this to work I intend to use a JSONString. The following code generates an empty file on the server (204 response):
HttpClient httpClient = new DefaultHttpClient();
String encoding = http_username + ":" + http_password;
encoding = Base64.encodeBase64String(encoding.getBytes());
HttpPut httpput = new HttpPut(http_path);
HttpEntity content=null;
try{
content = new StringEntity("hej");
}
catch(UnsupportedEncodingException e){
logger.error("Failed to Encode result");
}
logger.info("executing request " + httpput.getRequestLine());
try {
httpput.setHeader("Authorization", "Basic " + encoding);
//httpput.setHeader("Content-Type", "application/json; charset=utf-8");
httpput.setEntity(content);
HttpResponse response = httpClient.execute(httpput);
Header[] allHeaders = response.getAllHeaders();
for (Header h : allHeaders) {
logger.info(h.getName() + ": " + h.getValue());
}
} catch (Exception e) {
logger.error(e.getMessage());
}
I have tried both setting a content type and not doing it, no difference. What basic thing am I doing wrong?
Turns out that Base64.encodeBase64String appends a newline character at the end of the string, which throws everything off!
String encoding = http_username + ":" + http_password;
encoding = Base64.encodeBase64String(encoding.getBytes());
encoding= encoding.replace("\r\n", ""); //This fixes everything
Wow, that just took me a couple of days to figure out!

Categories

Resources