JSP make http get request and get json response - json

I would like to make a http get request which gets a json response. In that session response I would like to store a value into my session. How is this achievable?
Thanks

Here is the sample code. You'll have response in recvbuff.
<%#page import="java.io.*" %>
<%#page import="java.net.*" %>
<%
String recv;
String recvbuff;
URL jsonpage = new URL("http://www.yoursite.com/jsonresponse");
URLConnection urlcon = jsonpage.openConnection();
BufferedReader buffread = new BufferedReader(new InputStreamReader(urlcon.getInputStream()));
while ((recv = buffread.readLine()) != null)
recvbuff += recv;
buffread.close();
System.out.println(recvbuff);
%>

Related

Extracting values from certain fields in a json api request. (Ruby)

Attempting to extract the field "searched_count" in Udemy's API, but I'm not sure about the syntax.
If anyone can point me in the right direction, it will be highly appreciated. I'm using Sinatra and parsing the api request using net/http.
require 'sinatra'
require 'net/http'
require 'json'
require 'openssl'
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
def get_search_count(term)
url = 'https://www.udemy.com/api-2.0/search-suggestions?q=java'
uri = URI(url)
response = Net::HTTP.get(uri)
JSON.parse(response)
return response ["results"][0]["searched_count"]
end
get '/' do
return get_search_count("java")
end
I'm attempting to display the number on the web page. I don't receive any errors while I'm running it, but I can't tell if I'm actually receiving feedback from the request.
If it helps, here's a snippet from the json file:
{
"results": [
{
"_class": "search_log",
"id": 88,
"phrase": "java",
"searched_count": 3749730,
"url": "/courses/search/?q=java"
},
Edit: Here's my attempt at showing it on the web page. Located in index.erb
<html>
<head>
<title><%= #title %></title>
</head>
<body>
<h1><%= #headline %></h1>
<p><%= #paragraph %></p>
<form action="/action_page.php" method="get">
Search Term: <input type="text" name="term"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Also, my updated code in web.rb :
require 'sinatra'
require 'net/http'
require 'json'
require 'openssl'
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
def get_search_count(term)
url = 'https://www.udemy.com/api-2.0/search-suggestions?q=java'
uri = URI(url)
response = Net::HTTP.get(uri)
parsed_response = JSON.parse(response)
return parsed_response ["results"][0]["searched_count"]
end
get '/' do
return get_search_count("java")
end
get '/term' do
erb :index
end
get '/action_page.php' do
return get_search_count(params[:name])
end
Please change the method to something like this
def get_search_count(term)
url = 'https://www.udemy.com/api-2.0/search-suggestions?q=java'
uri = URI(url)
response = Net::HTTP.get(uri)
parsed_response = JSON.parse(response)
return parsed_response ["results"][0]["searched_count"]
end
NB:If you are getting the response properly it will work.

AEM inserts html info comment into json

I have the following jsp
<%
JSONObject jsonResult = new JSONObject();
response.setContentType("application/json");
String parentNodePath = slingRequest.getRequestPathInfo().getResourcePath();
String url = getServerBaseUrl(sling) + parentNodePath.split("/jcr:content")[0] + ".html?cid=twitter";
UrlShortener urlShortener = sling.getService(UrlShortener.class);
String shortUrl = urlShortener.shorten(url);
String encShortUrl = URLEncoder.encode(shortUrl);
jsonResult.put("url", url);
jsonResult.put("shortUrl", shortUrl);
jsonResult.put("encShortUrl", encShortUrl);
%>
<%=jsonResult.toString()%>
It executed when I type in browser the following adress http://servername:port/path/to/page.urlshortener.html.jsp
As you see i have "application/json" contentType. Result must contain only json information, but there is html comment:
{
"url":"http://servername/content/app/test/test1/naps1.html?cid=twitter",
"shortUrl":"http://servername/1E4sZYJ",
"encShortUrl":"http%3A%2F%2Fservername%2F1E4sZYJ"
}
<!--
cq{
"decorated":false,
"type":"app/components/page/newsarticlepage",
"path":"/content/app/test/test1/naps1/jcr:content",
"selectors":"urlshortener",
"servlet": "Script/apps/app/components/page/contentpage/urlshortener.html.jsp","totalTime":276,"selfTime":276
}
-->
Also i saw, this comments inserted after every component, or executed jsp in any page.
How to turn off insertion of this comment?
The comments <!-- cq{ ... } --> are added for the authoring interface. They are not included on the publish instance where wcmmode is disabled. You can see this by adding wcmmode=disabled as a query param to the end of your url. Also you will have to remove the cf# or editor.html from the url.

How to retrieve data from json string in jsp send from the another page using ajax

I am developing a web application. I have get the value from the data base using jsp and displayed to the user. On certain action from the user, i want to load the another page which will require same values which are fetched from the database.
For this I have created json object of this data in page1.jsp and passed to the another page2.jsp.
Now I want to retrieve that data. I have tried with gunction getString() functions, but it gives null value.
my first page is which sends the json data
$.ajax({
type : "POST",
url: "./ProfileUser.jsp", // This not redirecting.
data: "jsonData=" + JSON.stringify(jsonobj),
dataType: "json"
});
$(location).attr('href',url); //This is redirecting, If I removed this then another page is NOT loading
and the jsp code where I am retrieving this data
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="com.google.gson.JsonObject" %>
<%#page import="org.codehaus.jettison.json.JSONObject"%>
<%
String jsonData = request.getParameter("jsonData");
JSONObject j =new JSONObject(jsonData);
String mobile = j.getAttribute("mobile"); //error occures here
%>
And i get error
type Exception report
message An exception occurred processing JSP page /ProfileUser.jsp at line 15
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: An exception occurred processing JSP page /ProfileUser.jsp at line 15
12: <%
13: String jsonData = request.getParameter("jsonData");
14: //JONObject userinfo = (JSONObject) new JSONTokener(jsonData).nextValue();
15: JSONObject j =new JSONObject(jsonData);
16: String mobile = j.getString("mobile");
17: %>
18: <!DOCTYPE html>
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
root cause
java.lang.NullPointerException
org.codehaus.jettison.json.JSONTokener.more(JSONTokener.java:89)
org.codehaus.jettison.json.JSONTokener.next(JSONTokener.java:99)
org.codehaus.jettison.json.JSONTokener.nextClean(JSONTokener.java:153)
org.codehaus.jettison.json.JSONObject.<init>(JSONObject.java:168)
org.codehaus.jettison.json.JSONObject.<init>(JSONObject.java:266)
org.apache.jsp.ProfileUser_jsp._jspService(ProfileUser_jsp.java:75)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
How can get this data in jsp?
Thank you.

Return JSON from one JSP to another?

Is it possible in one JSP to make a jQuery ajax callback to another JSP and have data returned?
I am trying to make the ajax call to Page2.jsp in the $(document).ready call in Page1.jsp
I am attempting to get JSON returned by "Page2.jsp"
I am running Tomcat locally to test.
I am seeing the JSON printed to the console, but not returned to the original calling method in Page1.jsp
Any ideas?
Page1.jsp
$(document).ready(function(){
$.ajax({
url : 'Page2.jsp',
dataType: 'json',
success : function(json)
{
var obj = jQuery.parseJSON(json);
}
});
});
Page2.jsp
<%#page contentType="application/json; charset=UTF-8"%>
<%#page import="org.json.simple.JSONObject"%>
<%
JSONObject json = new JSONObject();
json.put("amount","55.00");
json.put("tax","1.00");
String jString = JSONObject.toJSONString(json);
PrintWriter out = response.getWriter();
out.println(jString);
out.close();
%>
I tried the code in your question and the jQuery.parseJSON() code throw the following error: "SyntaxError: JSON.parse: unexpected character". On debugging I saw that the servlet code generated by tomcat includes out.write("\r\n"); I suspect that these character are causing the syntax error.
Nevertheless in the javascript I tried accessing the returned object using the dot notation without parsing it and I was able to so as if it were a JSON object. It appears that it is not necessary to parse the returned object.
The only modification I made to the JSP code was to remove the lines PrintWriter out = response.getWriter(); and out.close();

upload text files to server through html and then reading on server

I can already upload files and then read them on the server, I just have a problem with the extra data at the beginning of the input stream. My code in jsp:
<%
DataInputStream dis = new DataInputStream(request.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String strLine;
while ((strLine = br.readLine()) != null) {
out.println (strLine+"");
}
%>
I get this data at the beginning that I would like to skip
-----------------------------41184676334 Content-Disposition: form-data; name="data"; filename="data.txt" Content-Type: text/plain
and also this at the end
-----------------------------41184676334--
I would to make an universal solution for this for any text file.