getting string on my browser output while testing servlet - java

I am running the following servlet and I am getting some weird output on my browser.The program is working fine without any errors but for some reason, the output of the line out.println(Add_To_Queue("abc","xyz","pqr")); is getting displayed
in the form of java string as shown below the code:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
out.println("<!DOCTYPE> html"); // HTML 5
out.println("<html><head>");
out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
out.println(Test_Servlet("abc","xyz","pqr"));
out.println("<head><title>TEST SERVLET API Call</title></head>");
out.println("<body>");
out.println("<h3>TEST SERVLET</h3>");
// Tabulate the request information
out.println("</body></html>");
}
finally {
out.close(); // Always close the output writer
}
}
public static Object Test_Servlet(String FirstString,String Secondstring,String ThirdString) throws IOException {
String accessKey = "myaccesskey";
String secretKey = "mysecretkey";
String uRLCppList = "http://myurl.com";
String method = "POST";
java.util.Date currentTime = new java.util.Date();
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
// Give it to me in GMT time.
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String dateTimeString = sdf.format(currentTime);
String signature = generateSignature(method, secretKey, dateTimeString);
String authorization = accessKey + ":" + signature;
Map<String, String> params = new HashMap<String, String>();
params.put("Content of first String", FirstString);
params.put("Content of Second String", Secondstring);
params.put("Content of Third String", ThirdString);
String[] result = sendHttpRequest(uRLCppList, "POST", params, dateTimeString, authorization);
return result;
}
Here is the browser output:
html [Ljava.lang.String;#430bc84a
TEST SERVLET
I am using JDK 8, ApacheTomcat 6, Netbeans 7.4 for deployment. I suspect, the result which is getting returned in the variable result defined inside Test_Servlet method is not getting displayed properly on the web browser.
Additional Code for SendHttpRequest method:
public static String[] sendHttpRequest(String requestUrl, String method, Map<String, String> params, String dateTimeString, String authorization) throws IOException {
List<String> response = new ArrayList<String>();
StringBuffer requestParams = new StringBuffer();
if (params != null && params.size() > 0) {
Iterator<String> paramIterator = params.keySet().iterator();
while (paramIterator.hasNext()) {
String key = paramIterator.next();
String value = params.get(key);
requestParams.append(URLEncoder.encode(key, "UTF-8"));
requestParams.append("=").append(URLEncoder.encode(value, "UTF-8"));
requestParams.append("&");
}
}
URL url = new URL(requestUrl);
URLConnection urlConn = url.openConnection();
urlConn.setRequestProperty("accept", "application/json");
urlConn.setRequestProperty("datetime", dateTimeString);
urlConn.setRequestProperty("authorization", authorization);
urlConn.setUseCaches(false);
// the request will return a response
urlConn.setDoInput(true);
if ("POST".equals(method)) {
// set request method to POST
urlConn.setDoOutput(true);
} else {
// set request method to GET
urlConn.setDoOutput(false);
}
if ("POST".equals(method) && params != null && params.size() > 0) {
OutputStreamWriter writer = new OutputStreamWriter(urlConn.getOutputStream());
writer.write(requestParams.toString());
writer.flush();
}
// reads response, store line by line in an array of Strings
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
return (String[]) response.toArray(new String[0]);
}

Your Test_Servlet method is returning an array of String. The result of calling toString() on an array is the string you're getting which includes the type and the object Id.
Not sure exactly what you're trying to do but you could put the strings out by iterating through the returned array.

html [Ljava.lang.String;#430bc84a
html comes from the out.println("<!DOCTYPE> html"); where you need to close the tag.
The [Ljava.lang.String;#430bc84a is the default to toString for an array of strings, telling you where the reference exists. The [ - means array and what follows is the type which happens to be java.lang.String. This is JVM level output
Id do something like:
String resultStr = "";
for(String s: result){
//format however you wish, this separates each element by a space
resultStr += s + " ";
}
return resultStr
If you want to put the results in a table or something, you could return the array and use the same for loop to encapsulate each element in a tag. The choice is yours and either works fine

Related

cannot pass the json value to function

I am going to get the JSON from the localhost db. Then, I want to put the json into ArrayList. I want to call the parseJSON function. But the JSON is null. Where I should call the function, thanks so much:))
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
StringBuilder sb = new StringBuilder();
InputStream input = con.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
parseJSON(json);
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON(
);
getJSON.execute();
}
private void parseJSON(String json) {
Gson gson = new Gson();
Type type = new TypeToken<List<EssayElement>>(){}.getType();
List<EssayElement> mList = gson.fromJson(json, type);
for (EssayElement essayElement : mList){
Log.i("Message: " +
"", essayElement.id + "-" + essayElement.title + "-" + essayElement.essay + "-" + essayElement.date + "-" + essayElement.time);
}
}
null object reference with String"json"
I would suggest using a proper http library that handles making requests for you like Volley or Retrofit... JSON and Error handling are also builtin, so AsyncTask can completely be removed for that purpose
But what you have is fine, only json shouldn't be used after the while loop, it's only the last line of the http response, not the full json (assuming there's multiple lines)
You should really consider parsing the results in the onPostExecute, and possibly even having the parse method return an actual object, or display to the UI
You are appending the string to StringBuilder sb = new StringBuilder();. You have to call like this parseJSON(sb.toString()); cause String json is just a pointer doesn't hold the actual string, you want.
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
String json = sb.toString();
You can instead use my code snippet it's working fine for me. now you can use son variable for your private void parseJSON(String json) function.

encode json object params in httpurlconnection

I want post some parameters to server with httpurlconnection in android,my data is an nested JsonObject , and i must encode it first but it's wrong because i receive status error from server, this is my encode function and Jsonobject:
private static String encodeParams(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
my nested json:
JSONObject postDataParams = new JSONObject();
postDataParams.put("name", "Manjeet");
postDataParams.put("email", "manjeet#gmail.com");
JSONObject par = new JSONObject();
par.put("class", "a");
par.put("family", "aray");
postDataParams.put("par", par);
Construct a URI from the output, only encoding the characters ?#/
which is a lot easier than your loop
You can use URI's, which produce a different output and result
The following sample
new URI("http", "host.com", "/path/", "key=| ?/#ä", "fragment").toURL();
produces the result http://host.com/path/?key=%7C%20?/%23ä#fragment. Note how characters such as ?&/ are not encoded to allow for the URI Query string
(Copied from the API)
I'am not sure about this code, since i've never worked with JSONObject, but i'll try to show you the idea :
Create a method which returns all the properties of an object (including the nested one) :
Map<String, String> jobjectToMap(JSONObject jo) {
Map<String, String> properties = new HashMap<String, String>;
Iterator<String> itr = jo.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = jo.optJSONObject(key);//this will returns null if the value is not a JSONObject from https://docs.oracle.com/middleware/maf242/mobile/api-ref/oracle/adfmf/json/JSONObject.html#getJSONObject-java.lang.String-
if(value != null) { //nested object
properties.putAll(jobjectToMap(value));
} else {
properties.put(key, jo.get(key)); //primitive one
}
}
return properties;
}
Create another method which transforms the map to an url
public String queryParams(Map<String, String> params)
throws UnsupportedEncodingException
{
StringBuilder queryString = new StringBuilder();
if (params.size() > 0) {
queryString.append('&');
}
// Convert the params map into a query string.
for (Map.Entry<String, String> entry : params.entrySet())
{
String encodedKey = URLEncoder.encode(entry.getKey(), "UTF-8");
String encodedValue = URLEncoder.encode(entry.getValue(), "UTF-8");
queryString.append(encodedKey);
queryString.append('=');
queryString.append(encodedValue);
}
return queryString.toString();
}

Getting string from json object not working

I am using gson library to get the json from an http request.
Everything works fine, except the part where I compare the string I received from the request. Even if the string are exactly the same, for some reason string.equals method fails. And as output it prints always different dates.
What is the reason for this behaviour? What am I missing here?
BufferedReader br;
try{
String url = "http://date.jsontest.com/";
URL request_url = new URL(url);
HttpURLConnection conn = (HttpURLConnection)request_url.openConnection();
conn.setRequestMethod("GET");
if (200 == conn.getResponseCode()){
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String jsonLine = "";
String line ;
while ((line = br.readLine()) != null) {
jsonLine += line;
}
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = jelement.getAsJsonObject();
try{
String result = jobject.get("date").toString();
System.out.println("res: " + result);
if(result.equals("05-29-2017"))
System.out.println("Same date");
else
System.out.println("different date");
}
catch (NullPointerException ex){ }
}
}
catch (JsonSyntaxException ex){}
catch (IOException ex) {}
String result = jobject.get("date").toString();
The above line returns String representation of date, i.e. with quotes around it : "05-29-2017" and that's why equals method returns false ("\"05-29-2017\"".equals("05-29-2017") will be false due to double quotes in the start and end)
If you want the actual value, you need to use getAsString method, e.g. following should work:
String result = jobject.get("date").getAsString();
if(result.equals("05-29-2017"))
System.out.println("Same date");
else
System.out.println("different date");

Parse HTTP JSONObject response in java

From the endpoint "test" I am returning a JSONObject:
#POST("/test")
#PermitAll
public JSONObject test(String name) {
JSONObject jsonval=new JSONObject();
json.put("key1",true);
json.put("key2","test");
return json;
}
in the method that checks the returned value I want to search for value of "key1".
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json = null;
String res = "";
while ((res = in.readLine()) != null) {
json += res + "\n";
}
in.close();
if (jsonData has key1 with value true){
//do sth
}
else{
//do sth else
}
How can I parse the returned JSONObject?
Have you tried constructing the JSONObject from its string representation (see http://www.json.org/javadoc/org/json/JSONObject.html):
JSONObject result = new JSONObject(json)
where json is the string you've read from the InputStream
Note: you might have to strip the last new line char or even omit new lines altogether

org.json.JSONException: End of input at character 0 of while creating a JSON Object

I'm simply trying to create JSON object like that:
JSONObject jsonObject = new JSONObject(new JsonUtility().execute(UrlUtility.url + "/" + lessonUrl).get());
Error occurs here ^ with message received in catch block:
org.json.JSONException: End of input at character 0 of
JsonUtility class as follows (I belive problem lies not there but still):
private class JsonUtility extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String result = "";
try {
InputStream inputStream = new URL(params[0]).openStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
StringBuilder sBuilder = new StringBuilder();
// Reading Json into StringBuilder
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
// Converting Json from StringBuilder to String
result = sBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
You see that response is concatenated from strings (due to application logic). The final string is: http://itvdn-api.azurewebsites.net/api/courses/test-driven-development/tdd-introduction. As you see when I redirect to that link it gives JSON response.
I have tried to evaluate this UrlUtility.url and received that:
That weird ending of char array confuses me. Perhabs its the problem. Tried to replace those characters using String.replaceAll("'\u0000'0", "" ). Didnt work.
Please help. Will appreciate any ideas. Thanks.
EDIT:
Also, when I hardcode link as:
JSONObject jsonObject = new JSONObject(new JsonUtility().execute("http://itvdn-api.azurewebsites.net/api/courses/test-driven-development/tdd-introduction").get());
It works!
EDIT #2 # ρяσѕρєя K
result = sBuilder.toString(); is empty - "" since it can't parse that concatenated string.
Note: I've been using the same parser with different links in this application e.g. http://itvdn-api.azurewebsites.net/api/courses and that was working fine (but there was no concatenation with link)
/**
* Convert InputStream into String
* #param is
* #return
* #throws IOException Throws an IO Exception if input stream cannot be read
*/
public static String stringFromInputStream(InputStream is) throws IOException {
if (is != null) {
byte[] bytes = new byte[1024];
StringBuilder x = new StringBuilder();
int numRead = 0;
while ((numRead = is.read(bytes)) >= 0)
x.append(new String(bytes, 0, numRead));
return x.toString();
}
else {
return "";
}
}
Use this method for reading the inputstream and get the string.

Categories

Resources