Request header is returning NULL - java

I have some issue with the code below, req.getHeader() is returning NULL
// The code below returns the expected value
String header = req.getHeader("x-key");
String size = req.getHeader("x-size");
String contentType = req.getContentType();
logger.info("Content-Length: " + req.getContentLength());
logger.info("x-key : " + header);
logger.info("x-size : " + size);
// The value of req.getHeader below is returning NULL
for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) {
String headerName = (String) e.nextElement();
logger.info("Name = " + headerName + " " + "Value = " + req.getHeader(headerName ));
}
What could be the problem?

Your code looks OK. If getHeader() returns null the header is indeed null, i.e. was not sent by client.
So, first check your client and be sure it sends the header. Second, try to use network sniffer, e.g. Wireshark and record the network activity.
If you need more assistance please post your client's code.

The below is part of the extract from the api docs.
public java.util.Enumeration getHeaderNames()
Some servlet containers do not allow servlets to access headers using this method, in which case this method returns null

Related

java: Can't check this string

Can’t convert String into json, and it seems that it will be superfluous for the entire string.
Was thinking maybe json might have helped me out here, but it doesn't seem to give me what I want or I don't know how it will be work.
How I can check the string?
I need to check:
METHOD: GET and URL: http://google.com/
also to check the BODY contains the fields userId, replId and view (no values, only keys)
I was trying to find a way to check that:
if (msg.contains("METHOD: GET") && msg.contains("URL: http://google.com/") && msg.contains("BODY: etc...")) {
System.out.println("ok");
}
It doesn't work. Some values from BODY that are dynamic and that's why for BODY the check won't pass if it’s so hardcoded String. And I guess there're any better ways to do that.
I'd like to have something like:
Assert.assertEquals(
msg,
the expected value for METHOD, which contains GET); // same here for URL: http://google.com/
Assert.assertEquals(
msg,
the expected value for BODY that has userId, replId, and view fields); // or make this assertion for each field separately, such as there is an assertion for the userId field, the same assertions for replId and view
And here's the String:
String msg = "METHOD: GET\n" +
"URL: http://google.com/\n" +
"token: 32Asdd1QQdsdsg$ff\n" +
"code: 200\n" +
"stand: test\n" +
"BODY: {\"userId\":\"11022:7\",\"bdaId\":\"110220\",\"replId\":\"fffDss0400rDF\",\"local\":\"not\",\"ttpm\":\"000\",\"view\":true}";
I can't think of any way to check that. Any ideas?
You can use the java.util.List Interface (of type String) and place the string contents into that list. Then you can use the List#contains() method, for example:
String msg = "METHOD: GET\n" +
"URL: http://google.com/\n" +
"token: 32Asdd1QQdsdsg$ff\n" +
"code: 200\n" +
"stand: test\n" +
"BODY: {\"userId\":\"11022:7\",\"bdaId\":\"110220\",\"replId\":\"fffDss0400rDF\",\"local\":\"not\",\"ttpm\":\"000\",\"view\":true}";
// Split contents of msg into list.
java.util.List<String> list = Arrays.asList(msg.split("\n"));
if (list.contains("METHOD: GET")) {
System.out.println("YUP! Got: --> 'METHOD: GET'");
}
else {
System.out.println("NOPE! Don't have: --> 'METHOD: GET'");
}
I've tried to use Assert:
String[] arr1 = msg.split("\n");
Map<String, String> allFieldsMessage = new HashMap<>();
for (String s : arr1) {
String key = s.trim().split(": ")[0];
String value = s.trim().split(": ")[1];
allFieldsMessage.put(key, value);
}
Assert.assertEquals(
allFieldsMessage.get("METHOD"),
"GET"
);
And the same for URL. But my problem is in BODY part. I thought maybe try to parse this particular part of String into json and then only check the necessary keys.

Empty Mysql field (NULL) ends up being a string "null" in Java

I have some data extracted from a MySQL database where some fields are NULL. Not accidentally as a string but properly stored as NULL. When I send these null-data JSON-encoded to my android app, they end up being a string "null" of length 4. So I rebuilt this problem condensed to the essential code:
PHP:
$string = null;
echo $array[0]['alt_names'] = $string;
echo json_encode($array);
Java: (My PHP class returns a string, in this case jsonResult)
Log.i("Tag", "result = " + jsonResult); // result = [{"alt_names":null}]
JSONArray jsonArray = new JSONArray(jsonResult);
Log.i("Tag", "jsonArray = " + jsonArray); // jsonArray = [{"alt_names":null}]
JSONObject jsonObject = new JSONObject(jsonArray.getJSONObject(0).toString());
Log.i("Tag", "jsonobject = " + jsonObject); // jsonobject = {"alt_names":null}
String test = jsonObject.get("alt_names").toString();
Log.i("Tag", "test: " + test); // test: null
Log.i("Tag", "test.length(): " + test.length()); // test.length(): 4
The missing quotation marks (not) enclosing null in the Log-output show me, that this is not a string "null" butt actually null. Nevertheless the string's length is 4 and this is true:
if (test.equals("null")) {Log.i("Tag", "true");} // true
What do I not understand? Thanks in advance!
Don't do a toString() on the object return by jsonObject.get("alt_names"). It is actually the static instance of JSONObject.NULL
Object test = jsonObject.get("alt_names");
System.out.println(test == JSONObject.NULL); // true
System.out.println(test.equals(null)); // true
System.out.println(jsonObject.isNull("alt_names")); // true
From javadoc :
It is sometimes more convenient and less ambiguous to have a NULL object than to use Java's null value. JSONObject.NULL.equals(null) returns true. JSONObject.NULL.toString() returns "null".

HTTP 400 response Servlet

The below code is part of a servlet which is taking the cookie value and sending request to another service with the same cookie value with additional headers.
I am getting HTTP 400 response on the responseCode = serviceUrlConnection.getResponseCode(); and on is = serviceUrlConnection.getInputStream();.
With the same input values (cookie and additional headers), I able to get correct output from the service using SOAP UI. Could somebody point out the mistake.
URL serviceURL = new URL(serviceUrlInput);
logger.info(" Validate Test token service Url" + serviceUrlInput);
URLConnection serviceConnection = serviceURL.openConnection();
HttpURLConnection serviceUrlConnection = (HttpURLConnection)serviceConnection;
serviceUrlConnection.setRequestProperty("Content-Type", "application/json");
serviceUrlConnection.setRequestProperty("charset", "UTF-8");
String TestCookieValue = null;
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals("Test")) {
//TestToken = cookies[i].getValue();
TestCookieValue = cookies[i].getValue();
logger.info("Test cookie : " + "Test=" +TestCookieValue);
//serviceUrlConnection.setRequestProperty("Cookie", TestCookie.substring(0, TestCookie.indexOf(';')));
serviceUrlConnection.setRequestProperty("Cookie", "Test=" +TestCookieValue);
break;
}
}
}
//Set the timestamp in the header
Date javaUtilDate = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
String formattedDateTime = formatter.format(javaUtilDate);
serviceUrlConnection.setRequestProperty("timestamp", formattedDateTime);
logger.info(adapterDescription + " :: timestamp added with value :: " + formattedDateTime);
//Set the transactionId header
UUID uuid = java.util.UUID.randomUUID();
serviceUrlConnection.setRequestProperty("transactionId", uuid.toString());
logger.info(adapterDescription + " :: transactionID added with value :: " + uuid.toString());
//Set the sourceSystem header
String sourceSystem = + InetAddress.getLocalHost().getHostName();
serviceUrlConnection.setRequestProperty("sourceSystem", sourceSystem);
logger.info(adapterDescription + " :: sourceSystem added with value :: " + sourceSystem);
int responseCode;
serviceUrlConnection.setDoOutput(true);
wr = new DataOutputStream(serviceUrlConnection.getOutputStream());
wr.writeBytes("");
logger.info(adapterDescription +" :: " + wr);
responseCode = serviceUrlConnection.getResponseCode();
logger.info(adapterDescription +":: responseCode :: " + responseCode);
is = serviceUrlConnection.getInputStream();
Error 400 means that there's something wrong with your request. A few things to check:
Is the server really expecting a GET request, not a POST? To do a post you can call serviceUrlConnection.setRequestMethod("POST")
You are settings setDoOutput(true) but are not writing anything in the request. Maybe you need to write some content.
By default the request method is GET. So, If no data need to be sent over, we dont need to set the DataOutputStream and also no need to call setDoOutput(true)
/*
Commented out the below lines:-
wr = new DataOutputStream(serviceUrlConnection.getOutputStream());
serviceUrlConnection.setDoOutput(true);
*/
See an exiting SO question :-
HttpURLConnection sends a POST request even though httpCon.setRequestMethod("GET"); is set

Null values on reading custom JAD attributes

I have a blackberry Application. It is downloaded from a web page which provides dynamic JAD file content. The JSP prints those :
out.println("Appid: " + appid);
out.println("Ip: " + user.getIp());
out.println("Servicename: " + service);
out.println("MIDlet-Version: 1.0.0");
out.println("MIDlet-Jar-URL: MyApp.jar");
out.println("MIDlet-Jar-Size: 91633");
out.println("MicroEdition-Profile: MIDP-2.0");
(and other attributes goes on like that..)
I need to get my custom attributes like "Appid" but it sometimes gets null values. User can download and run the app, but some of them cannot get my custom attributes. I dont know it is about the phone model or the current state of OS, but according to my logs, this problem appears mostly on those devices :
9800 with OS 6.0.0.546
9300 with OS 6.0.0.570
9300 with OS 6.0.0.668
9320 with OS 7.1.0.398
My code to get attributes :
CodeModuleGroup cmg = null;
CodeModuleGroup[] allGroups = CodeModuleGroupManager.loadAll();
String moduleName = ApplicationDescriptor
.currentApplicationDescriptor().getModuleName();
for (int i = 0; i < allGroups.length; i++) {
if (allGroups[i].containsModule(moduleName)) {
cmg = allGroups[i];
break;
}
}
if (cmg != null) {
AppData.firstPageURL = cmg.getProperty("Firstpage");
AppData.appId = cmg.getProperty("Appid");
AppData.firstIp = cmg.getProperty("Ip");
AppData.firstSubServiceName = cmg.getProperty("Servicename");
for (Enumeration e = cmg.getPropertyNames(); e.hasMoreElements();) {
String name = (String) e.nextElement();
String value = cmg.getProperty(name);
AppData.errorStep += "-" + name + ":" + value + "-";
}
}
By the way, I determined that the code in the for loop above never runs in these cases.
Any idea ?
Sometimes, ApplicationDescriptor.currentApplicationDescriptor().getModuleName() gives the name of the sibling cod file instead of the main cod file. So, if your module name is MyApp, the function may return MyApp-1.
To solve this, you have to strip out the number after the hyphen.
String moduleName = ApplicationDescriptor.currentApplicationDescriptor()
.getModuleName();
if(moduleName.indexOf('-') > 0) {
moduleName = moduleName.substring(0, moduleName.indexOf('-');
}

Setting the encoding

Is there a way to set the enconding for the object requestBuilder. I have this code, which adds paramters to an URL. But when I add some character from the ISO-Latin I dont get the correct enconding:
while(kvEnum.hasMoreElements()) {
KeyValue kv = (KeyValue) kvEnum.nextElement();
String key = kv.key;
String value = kv.value;
System.out.println("######param added - "+ "key: "+key + ", value: "+value);
requestBuilder = requestBuilder.appendQueryParameter(key, value);
}
Documentation for requestBuilder.appendQueryParameter(key, value); says that encodes, but not which type of coding is using.

Categories

Resources