How do I obtain the response from google volley on Android? - javascript

How do I obtain the response from google volley? I'm able to display the response in my logcat using System.out.println("Volley"+response);
I cant figure out how to pull it out of the google volley function. Heres my code:
final String url = MAIN_URL;
// prepare the Request
StringRequest sr = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("Volley"+response);
//I want to be able to get this response and use it in other functions.
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("Error"+error);
}
});
// add it to the RequestQueue
sr.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(sr);

I always put queue into singleton - Application and request can be called and received wherewer in the code, fom example:
android volley caching asynchronous requests - How te get url of the request in ResponseListener
So you just create your own response listener in the class where you need it

Related

sending images from java webserver to client

i'm new to java web App i was trying to create simple chat webapp that send images to webserver then the server will send them to other client at first i had problem that the websocket wont send large data so i send my images using
http request
after encoding them to base64 then after i was able to decode it and store it,i was trying to seend it from the server to the other client
i did not find any solution the only way to send it to the other client is using websocket
this is the third day of searching and i'm thinking of given up since there is no resources for noobies
i saw alot of code but they was in high level i hope if some one have the answer of
How can i send the image to the client ?
please Try to explain it in a simple way
the javascript function responsible for sending the img
send=function () {
var file =document.getElementById("image").files[0];
var content_type ={
headers:{
"content-type" : "multipart/form-data"
}
};
var formdata = new FormData();
formdata.append('image',file);
axios.post('AddImage',formdata,content_type)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
the post method that send the file
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Part file=request.getPart("image");
InputStream in = file.getInputStream();
byte[] Byte_file = new byte[in.available()];
in.read(Byte_file);
String encodedString = "{encodedString : "+"data:image/png;base64,"+new String(Byte_file)+"}";
//sending the String to the other client via his session
socket.session.getAsyncRemote().sendText(encodedString);
}

How to redirect/forward to a new html page with variable content?

The problem
I'm creating a web app where the user is served a login page, login.html, and has to enter his credentials. The servlet class grabs the information using ajax in the form of a POST request, generated by the user clicking the submit button. After checking the correctness of the credentials, i wish to serve the user with a new HTML page, a welcome page, where the response of the servlet is transferred. The problem i'm facing is how to transfer the response from a starting LoginServlet class to a WelcomeServlet all the meanwhile, the client is projecting a new HTML page, welcome.html, and catch the response of the WelcomeServlet in an ajax call made by a js script in the new HTML page.
Background
I'm just starting to delve into the development of web-apps, so if i'm mistaken in any part of my logic and understanding of the whole frontend-to-backend process, please say so. I'm aware of the redirect() and forward() functions but i'm not understanding the way these functions can be used in conjunction, or the complete difference, with the client side of things.
I have the following servlets:
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher("welcomeservlet");
dispatcher.forward(request, response);
}
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 2L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//parse request and send response
}
In the login.html file i've included the following js code:
function loadNewPage() {
// retrieve data and store them in a js Object
$.ajax({
url: "loginservlet",
type: 'POST',
dataType: 'json',
data: JSON.stringify(jsObject),
contentType: 'application/json',
mimeType: 'application/json',
success: function (data) {
window.location.href = "welcome.html";
},
error: function (data, status, er) {
alert("error: " + data.text + " status: " + status + " er:" + er);
}
});
}
I'm not including another js script which would be placed inside the welcome.html purposely since i don't know what would i have to add in there to catch the response of the new servlet. A possible reason why this whole thing isn't working could be that i'm missing something in the functionality of the forward() function but couldn't find an example online that does the exact thing that i want to do.
(Image credit w3schools)
The fact is you can't jump to another servlet. Ajax response will be sent back to the same webpage from which request was generated.
For your requirement what you can do is, Check whether login is success or not in LoginServlet. If yes create a token, save it in database along with the username and send the same token as response to the client.
Now in client save the token in localStorage and redirect to welcome.html.
On welcome.html page loading check whether token saved in localStorage exists or not. If yes, check whether it's valid or not. If valid the call WelcomeServlet . Else display login screen.
It's called token based authentication. You can read more about it here

Get HTTP Response before Async call in gwt

I want to get the Http Response of URL in gwt before the Async method calls.
Below is my working code but i want to execute it before the Async call.
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, "http://localhost:8080");
try {
builder.sendRequest(null, new RequestCallback() {
#Override
public void onResponseReceived(Request request, Response response) {
}
#Override
public void onError(Request request, Throwable exception) {
throw new UnsupportedOperationException("Not supported yet.");
}
});
} catch (RequestException ex) {
}
return response.getStatusCode();
Also note that i am using JavaScript in my project. Is there any way to write this code in javaScript and retrieve the response in my OnModuleLoad method?
Any suggestions will be highly appreciated.
I have made the simple function in javascript with async : false. Then i hit the url and get the response.
This response will be taken in onModuleLoad using native method. Sync calling.
Solved :-)

Correct way of making POST request with JSON in SPRING MVC?

I am fairly new to spring and want to the correct way of making post request. I have a list of json object that I want to post to my server
for example
var list = [{name:"abc",age:23},{name:"xyz",age:22},{name:"xcx",age:33}]
I am making a post request in google closure using xhr to my server in this fashion
model.xhrPost(id,url,"list="+JSON.stringify(this.list),callback);
This is what my controller looks like
#RequestMapping(value={"/getInput"}, method = RequestMethod.POST)
#ResponseBody
public String logClientError(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws Exception{
JSONObject result = new JSONObject();
try{
String errorObj = request.getParameter("list");
JSONArray errors = new JSONArray(errorObj);
some more code here which loops through the list...
result.put("isSuccess", true);
return result.toString();
}catch(JSONException e){
result.put("isSuccess", false);
return result.toString();
}
}
So in short I am making a post request by passing querystring parameter. Is this the correct way or should the content be posted in the body? If I post in the body what changes do I have to make ?
This is definitely not how you should post the data to REST endpoint. Going this way you can use GET instead of POST and it will work as well. However POST should be definitely used to create new resource and the content should be carried in message body not as a query param.
On the backend side you can catch and parse the content yourself or create a class (see below) that will be filled with data from body.
DTO:
class Person {
String name
Integer age
}
class PersonList {
List<Person> persons
}
Endpoint:
public String logClientError(#RequestBody PersonList list, HttpServletRequest request, HttpServletResponse response) throws Exception
Body:
{
"persons": [{name:"abc",age:23},{name:"xyz",age:22},{name:"xcx",age:33}]
}
#ResponseBody can be used in the same manner for responses.

How to perform Ajax call from Javascript to JSP?

I have a JavaScript from which I am making an Ajax Call to a JSP. Both JavaScript and JSP are deployed in the same web server. From JSP I am forwarding the request to one of the service (servlet) available in other web server using HttpURLConnection. I got the response in JSP, but now I need to pass the response back to JavaScript which made an Ajax Call. How I can do it?
My ultimate goal is to make an Ajax request from JavaScript to a JSP and from that JSP to one of the services and return the response back to JavaScript.
JSP is the wrong tool for the job. The output would be corrupted with template text. Replace it by a Servlet. You just need to stream URLConnection#getInputStream() to HttpServletResponse#getOutputStream() the usual Java IO way.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
URLConnection connection = new URL("http://other.service.com").openConnection();
// Set necessary connection headers, parameters, etc here.
InputStream input = connection.getInputStream();
OutputStream output = response.getOutputStream();
// Set necessary response headers (content type, character encoding, etc) here.
byte[] buffer = new byte[10240];
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
}
That's all. Map this servlet in web.xml on a certain url-pattern and have your ajax stuff call that servlet URL instead.

Categories

Resources