How to add a request header in Bayeux Client Request? - cometd

I am using the Bayeux Java Client, and I am trying to add a request header for all the
requests made to the server, including the handshake request.
Currently I am using :
mTransport = new LongPollingTransport(options, httpClient) {
#Override
protected void customize(ContentExchange exchange) {
super.customize(exchange);
if (mCrumb != null) {
exchange.addRequestHeader("Header Key", "Header value");
}
}
};
mClient = new BayeuxClient(HANDSHAKE_URL, mTransport);
Is this the right way? I am not able to get it to work?
Thanks,

That is the right way to do it.
In the CometD test suite there is a test that performs what you are doing.

Related

how to get a valid response from a php web service on GWT

I'm trying to get data from a php web service (that I've put in my localhost - tested and works fine) in the client side of my GWT application.
I've tried to use the following package com.google.gwt.http.client.* it looks like the code works fine but the response is always 0, it's highly likely to be a corss problem but I still can't figure how to solve it even though I've tried to use requestBuilder.setHeader(..);
here's the code I'm working on:
String url = "http://localhost/geoTrackerTest.php?id=15";
RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
requestBuilder.setHeader("Access-Control-Allow-Origin", "http://localhost");
requestBuilder.setHeader("Access-Control-Allow-Methods", "POST, GET, UPDATE, OPTIONS");
requestBuilder.setHeader("Access-Control-Allow-Headers", "x-http-method-override");
try {
Request request = requestBuilder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
GWT.log("Error: "+exception.getMessage());
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
GWT.log("response: "+response.getText());
} else {
GWT.log("response code: "+response.getStatusCode());
}
}
});
} catch (RequestException e) {
GWT.log("Request Exception: "+e.getMessage());
}
I'm still getting 0 as a response.
You will need to set the header in response from server side (not from the GWT client side), then you can make Cross Site Requests from GWT RequestBuilder. Something like this on server side:
Response.setHeader("Access-Control-Allow-Origin","http://localhost");
If you only need to send GET requests, you can use JSONP (http://www.gwtproject.org/javadoc/latest/com/google/gwt/jsonp/client/JsonpRequestBuilder.html) instead to send cross domain requests, without headers setting on server side.

Unable to set values in the map using webclient call response

I am unable to get values filled in the map after making a web client call and using the response of the previous Mono.Here is the code I have tried.The value of parameters.size() comes out to zero.Not able to get the reason as to why the value is not filled.I basically want to return age ( and not Mono object)
from this method.Using block gives an error block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-3.
Map<String, String> parameters = new HashMap<String,String>();
Mono<Person> obj = webClient
.post()
.uri("dummy url")
.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
.retrieve()
.bodyToMono(Person.class)
.flatMap(resp -> {
parameters.put("name", resp.getName());
parameters.put("age", resp.getAge());
return Mono.just(new Person(resp.getName(),resp.getAge()));
}
);
System.out.println(parameters.size());
Please suggest where I am wrong and solution to fix the same.
Since this is about collecting and using a token of some sort collected from a previous HTTP call, your best bet is to delegate all that to an ExchangeFilterFunction.
An ExchangeFilterFunction is a filter that is executed on the client side for each outgoing request. Here is a very, very naïve implementation of such a filter:
class TokenFilterFunction implements ExchangeFilterFunction {
private final AtomicReference<String> token = new AtomicReference<>();
#Override
public Mono<ClientResponse> filter(ClientRequest req, ExchangeFunction next) {
if (this.token.get() == null) {
return fetchToken(next).then(sendRequest(req, next));
}
else {
return sendRequest(req, next);
}
}
private Mono<ClientResponse> sendRequest(ClientRequest req, ExchangeFunction next) {
ClientRequest request = ClientRequest.from(req)
.header("Token", this.token.get()).build();
return next.exchange(request);
}
private Mono<Void> fetchToken(ExchangeFunction next) {
ClientRequest tokenRequest = ClientRequest.create(HttpMethod.GET,
URI.create("https://example.com/token")).build();
return next.exchange(tokenRequest).doOnNext(res -> {
this.token.set(res.headers().header("Token").get(0));
}).then();
}
}
This could automatically call the token endpoint to fetch a token when needed and directly chain with the request you asked in the first place. Again, such an implementation should be much more complex than that, handling domains, errors, and more.
If you're using some authentication technology, such a filter might be implemented already in Spring Security in a much, much better way.
You can configure it on your client during the building phase, like:
WebClient webClient = WebClient.builder().filter(new TokenFilterFunction()).build();

HttpResponseException: Internal Server Error

Weirdest thing I have seen in a while. I run my API call through Postman and have no problems at all making a GET request. However, the groovy code below pulls groovyx.net.http.HttpResponseException: Internal Server Error. I am not able to pull even debug to understand if I am actually getting a 5xx error or my code is legitimately broken.
Additionally I have had code like this work in the past, I re-pulled that working code and have the same error. Curious if my Maven config settings would be causing the issue as well (Not sure where I would have to debug). I have also tried messing with the URIbuilder line to see if changing the endpoints would help.
Thanks for helping
abstract class HTTTPClient {
protected runGetRequest(String endpointPassedIn, RESTClient Client){
URIBuilder myEndpoint = new URIBuilder(new URI(Client.uri.toString() + endpointPassedIn))
//Error happens at the next Line
Client.get(uri: myEndpoint, contentType: ContentType.JSON)
LazyMap Response = unprocessedResponse.getData() as LazyMap
return Response
}
}
#Singleton(lazy = true)
class RequestService extends HTTTPClient {
private String auth = "myAuth"
private String baseURL = 'https://api.endpoint.net/'
private RESTClient client = setClient(baseURL, auth)
public buildResponseList(int pagesToPull) {
String endpoint = 'site/address.json?page='
ArrayList responseList = []
for (int i = 1; i <= pagesToPull; i++) {
LazyMap Response = runGetRequest(endpoint + i, client)
for (row in Response) {
responseList.add(row)
//TODO Add in items call here
}
}
return conversationList
}
The error was due to encoding in the Authorization, was on the server side, not the code side

How to fetch data of remote server in GWT development mode?

I'm a GWT beginner. I debug my program in GWT development mode. The url is http://127.0.0.1:8888/Replayer.html?gwt.codesvr=127.0.0.1:9997.
I want to get data from existing server which provided data in json format. My code is:
String url = "http://i.abc.com?sid=" + mSessionId + "&action=info";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
try {
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
// Couldn't connect to server (could be timeout, SOP
// violation, etc.)
Window.alert("Get fudao info error");
mPrepare = false;
}
#Override
public void onResponseReceived(Request request, Response response) {
GWT.log("statuscode:"+response.getStatusCode());
if (200 == response.getStatusCode()) {
// Process the response in response.getText()
Window.alert(response.getText());
mPrepare = true;
} else {
// Handle the error. Can get the status text from
// response.getStatusText()
Window.alert("Get fudao info wrong");
mPrepare = false;
}
}
});
} catch (RequestException e) {
// Couldn't connect to server
}
When run the application, the request failed and its status was "canceled". Is it the reason that I cannot request remote server address from localhost for SOP restrictions?
How to fetch data of remote server in GWT development mode?
Normally can't fetch data from another server form GWT client code. But your local server can serve as proxy, e.g. you sending request to your local server, it will send request to remote server, than it will get response from remote server and give it to the GWT client code. This is basically the easiest solution.

multiple pages with C# Web browser control

I am trying to download HTML content from any URL through webbrowser control in C#.net.
I choose webrowser to handle Javascript issues. I am using webbrowser control without placing
it on the form. It works great for one url, but when I call it for multiple urls I am unable
to download the page.
Here is the code
GetWebpage()
{
System.Windows.Forms.WebBrowser wb = new System.Windows.Forms.WebBrowser();
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
wb.Navigate(sURI, false);
bDocumentLoaded = false;
while (!bDocumentLoaded)
{
Application.DoEvents();
Thread.Sleep(100);
}
sHTML = wb.DocumentText;
bDocumentLoaded = false;
}
Event:
private void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
System.Windows.Forms.WebBrowser webBrowser1;
webBrowser1 = sender as WebBrowser;
string strTit = webBrowser1.DocumentTitle;
string str = webBrowser1.DocumentText;
bDocumentLoaded = true;
}
Cheers,
Karthik
You can use webclient object to fetch data from some url.
Try using Downloading String
public static void DownloadString (string address)
{
WebClient client = new WebClient ();
string reply = client.DownloadString (address);
Console.WriteLine (reply);
}
You can also use ASYC method of same downloading string.
I think your problem is that some sites are detecting specific browsertype and then they are returning HTML
Try setting the HeaderProperty of WebClient Object this is a list of HttpWebRequest Object
For Example
myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded");
Modify the useragent of HTTPWEBRequest then add to headers.
HTTPWEBRequest.UserAgent=".NET Framework Test Client";
You can check more information about this in MSDN Link
I might recommend using the mshtml and SHDocVW libraries and using approach found in the answer here:
Unable to to locate and click a submit button using mshtml.HTMLInputElement