How to send POST parameters with RequestBuilder? - gwt

I'm trying to make a POST request, but I'm not sure how to set parameters. Something like:
RequestBuilder rb = new RequestBuilder(RequestBuilder.POST, url);
StringBuilder sb = new StringBuilder();
sb.append("key1=val1");
sb.append("&key2=val2");
sb.append("&key3=val3");
rb.setRequestData(sb.toString());
that does not seem to be the current way, though. What's the right way to send params like this with the POST?

The answer should be in here Making POST requests with parameters in GWT Try with builder.setHeader("Content-type", "application/x-www-form-urlencoded");

It is opening new window but not passing Post parameters to new window using GWT.
rb.setRequestData(json);
Request response = rb.sendRequest(json.toString(), new RequestCallback() {
public void onError(Request request, Throwable exception) {}
public void onResponseReceived(Request request, Response response) {
Window.open(rb.getUrl(), postTarget, postWinFeatures);
}
});

Related

HTTP request doesn't work with a paricular rest

I'm making an application filled with various rest services, so I create a one-for-all HTTP class in order to allow a client application to keep asking information, via rest, to a server application
public HttpURLConnection HTTPSENDJSON(String urlAPI,String out,String requestmethod) throws IOException {
URL url = new URL(urlAPI);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestMethod(requestmethod);
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStream os = conn.getOutputStream();
System.out.println(out);
os.write(out.getBytes());
os.flush();
os.close();
return conn;
urlAPI is the desired URL, a string is the JSON string (I'm using GSON) and the requestmethod is a string in order to switch from PUT\POST\GET\PATCH.
So, as I wrote, it's all ok if I need to retrieve information from DB\insert a new record
ATM my Client application makes a call to the server who calls an EJB in order to CRUD the information.
this is the Client method who call the upper method (the HTTPSENDJSON )
public String modifica() throws IOException {
Universal_HTTPREQUEST httprequest = new Universal_HTTPREQUEST();
String url= "http://localhost:8080/ModuloWebClientNuovo/rest/clientela/modifica/account/"+ac.getId()+"";
Gson g = new Gson();
String out=g.toJson(ac, Account.class);
httprequest.HTTPSENDJSON(url, out,"PUT");
and this is the working (at least with POSTMAN) services
#PUT
#Path("modifica/account/{id}")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response modificaaccount(#PathParam("id") int id,Account a) {
System.out.println("i'm inside the api and i wrote: "+ a.toString());
ac.updateAccount(a);
return Response.status(200).entity(a).build() ;
}
The Client doesn't even make the call to the server, BUT the only with this specific rest, other works fine.
update account EJB is:
#Stateless
public class AccountEJB implements IAccountCrud {
#EJB
Iconnessioni x;
#Override
public void updateAccount(Account account) {
EntityManager entityManager=x.apriconnessione();
entityManager.merge(account);
x.chiudiconnessione(entityManager);
}
}
Fixed whit a new from scratch wildfly

How to display Excel, PDf files from Webservice on AEM pages

I'm trying to do the following: The response of a webservice is an excel (a separate call for pdf) file. I need to show this file as a link on the aem-page, and whne users click the link, the browser opens (or downloads) the file.
Use case: On the customer page, there is a section with links to Order History (Excel file), Invoice(PDF file), Products catalog(Excel file). Clicking on each link, makes a call to webservice and fetches the respective file.
how to achieve this?
With help from Scott:
http://help-forums.adobe.com/content/adobeforums/en/experience-manager-forum/adobe-experience-manager.topic.html/forum__xhh5-objective_therespo.html
Here's my solution:
From the UI, submit the action to Sling Servlet
<form name="importFileForm" method="get" action="/services/getData">
<input type="submit" title="Submit" value="Submit" name="bttnAction">
</form>
Your Servlet class
public class TTIGetServlet extends SlingAllMethodsServlet {
#Override
protected void doGet(SlingHttpServletRequest request,SlingHttpServletResponse response) throws ServletException,IOException {
...
...
String serviceurl = <<< your webservice url>>>
HttpClient httpclient = HttpClients.custom().build();
generateFile(serviceurl, httpclient, request, response);
RequestDispatcher dispatcher = request.getRequestDispatcher("/content/ttii/en/importfiletest.html");
dispatcher.forward(request, response);
}
}
Generate File method that pops up the file download on browser
public static void generateFile(String serviceurl,
HttpClient httpclient,
SlingHttpServletRequest httpRequest,
SlingHttpServletResponse httpResponse) throws ClientProtocolException, IOException {
HttpResponse response;
HttpGet httpGet = new HttpGet(serviceURL);
// Makes the call to WebService
response = httpclient.execute(httpGet);
// CORE LOGIC
if (response!=null) {
ContentType contentType = ContentType.getOrDefault(response.getEntity());
String mimeType = contentType.getMimeType();
if (mimeType.equals(MIMETYPE_JSON)) {
// Out of context here...
} else {
// SHOW THE FILE
ServletOutputStream sos = httpResponse.getOutputStream();
httpResponse.setContentType("application/vnd.ms-excel");
httpResponse.setHeader("Content-Disposition", "attachment;filename=test.xls");
BufferedHttpEntity buf = new BufferedHttpEntity(response.getEntity());
InputStream istream = buf.getContent();
sos.write(FileHelper.writeFiles(istream));
sos.flush();
}
}
}

GWT RequestBuilder Post Response return 0 StatusCode

I have created a very simple servlet that uses HTTP Post method. I have tested it on my local Apache Tomcat server using a simple HTML form that works. I want to integrate it with my GWT app. I am able to call it using FormPanel - in that case it downloads content and there is a flicker in my browser window.
I know I need to use RequestBuilder to access it. But my response.getStatusCode() in my overloaded public void onResponseReceived(Request request, Response response) method always return status as 0 and response.getText() return null
String url = "http://localhost:8080/servlets/servlet/ShapeColor";
builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url));
try {
String json = getJSONString();
//builder.setTimeoutMillis(10000);
builder.setHeader("Access-Control-Allow-Origin", "*");
builder.setHeader("Content-type", "application/x-www-form-urlencoded");
builder.sendRequest(json, new RequestCallback() {
#Override
public void onError(Request request, Throwable exception) {
Window.alert("Couldn't retrieve JSON");
}
#Override
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
System.out.println("res:"+response.getText());
} else {
System.out.println("err: " + response.getStatusCode()+","+response.getText());
}
}
});
//Request response = builder.send();
} catch (RequestException e) {
// TODO Auto-generated catch block
}
I have tried many thing including changing my servlet following CORS reference ( https://code.google.com/p/gwtquery/wiki/Ajax#CORS_%28Cross_Origin_Resource_Sharing%29 )
It always works on browser using my test.html, but not from my App. Although, onResponseReceived method always gets called
Thanks
KKM
Have you checked if your call in the app violates the Same-origin policy (http://en.wikipedia.org/wiki/Same-origin_policy) in some way? The GWT RequestBuilder uses XMLHttpRequest internally, so it does fall under the SOP.
Does your GWT app run inside the same domain (server + port) as the servlet? Does it use the same protocol (https or http)?

Tapestry, request processing from another application

i'have two web appli, tapestry appli and a simple web appli(servelt). in tapestry appli , i have a form, and when it'll be sent, i call a httpClient for sending some informations to author appli using apache's httpClient. like this
void onSubmitFromForm() {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://localhost:8080/appli2/recep");
post.setHeader("referer", "http://localhost:9090/app1/start");
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("_data", getData());
post.setEntity(new UrlEncodedFormEntity(param));
HttpResponse response = client.execute(post);
response ?????
} catch (Exception e) {
e.printStackTrace();
}
}
And in my servelt recep of the simple web appli(2) i do the same like below
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(request.getHeader("referer"));
post.setHeader("p",getP());
client.execute(post);
} catch (Exception e) {
e.printStackTrace();
}
}
So, my recep reviev data from my form but it'cannot response it, i'would that tapersty appli could recieve the param 'P' from the simple web appli ?
thanks
If I'm correct you want your tapestry application to POST some form data received from a form submit within Tapestry to a servlet running on another application.
If this is what you want then what is missing is the haneling of the request and constructing a response in your servlet. Because both your tapestry page and your servlet are POST'ing meaning neither constructs a response for your HttpClient to deal with.
In your servlet you could:
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.println(getP());
out.close();
}
And deal with the response in your tapesty form handler.

GWT - spring security - session timeout

I have a GWT + Spring Security web app. I was trying to add:
<security:session-management invalid-session-url="/X.html"/>
However, when I try to test this. It seems I see a:
com.google.gwt.user.client.rpc.InvocationException
with message as the HTML content of X.html. Can someone please advise on how to fix this?
Because GWT communicates with a server via Ajax RPC requests, the browser will not be redirected to X.html. What you need to do in your service calls is throw an exception if they are not authorized and handle in in void onFailure(Throwable caught) method of your AsyncCallback.
If you want to redirect to /X.html try:
Window.Location.replace(GWT.getHostPageBaseURL()+"X.html");
However, if you want to send the request to the server use RequestBuilder:
String url = GWT.getHostPageBaseURL() + "/X.html";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
try {
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
// invalid request
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
// success
} else {
// sth went wrong
}
}
});
} catch (RequestException e) {
// couldn't connect to server
}