I am using gwt with php.
I am trying to get data fom the http://typing.lc/userInfo.php url.
but the following code returns nothing, but response.getText() is 200, however when i ask http://typing.lc/userInfo.php through browser it returns value.
try
{
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, "http://typing.lc/userInfo.php");
builder.setHeader("Content-Type", "application/x-www-form-urlencoded");
builder.sendRequest("", new RequestCallback()
{
#Override
public void onError(Request request, Throwable exception)
{
Window.alert("Error");
}
#Override
public void onResponseReceived(Request request, Response response)
{
Window.alert("Success: " + response.getText());
}
});
}
catch (RequestException e)
{
Window.alert("Exception");
}
You are probably running into a SOP (Same Origin Policy) issue.
See here for possible solutions.
Related
I´m trying to get data from my api. In postman the request works, here´s the response:
{
"ips_Beacons_BeaconID": 14,
"ips_Beacons_BeaconDescription": "b2",
"ips_Beacons_BeaconLat": 12.3123,
"ips_Beacons_BeaconLon": 32.123,
"ips_Beacons_BeaconImgX": 45,
"ips_Beacons_BeaconImgY": 123
}
I´ve tried and i got the response with Okhttp. However it stopped working for some reason.
Although i got the response, i wish to serialize the json string it and instanciate objects. But i couldn´t get the response out of the onSuccess method inside the callback.
This is what i had that workd but doens´t work anymore:
OkHttpClient client = new OkHttpClient();
String url ="http://192.168.1.95:44374/api/beacons";
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) { e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()){
String myResponse = response.body().string();
listBeacons = objectMapper.readValue(myResponse, new TypeReference<List<Beacon>>(){});
Log.i(TAG, myResponse);
}
}
});
I need the listBeacons List to perform other operations outside this activity.
I've been working on a Java application that utilizes the openshift api. Specifically OpenShift deployment configuration
I have tried to set up a watcher, but my response body is never called. I am already able to get a response from the 'non watcher' APIcalls. I am using the groovy httpbuilder library to fulfill my request
def http = new HTTPBuilder(<<URL TO OPENSHIFT>>)
try {
http.get(path: '/oapi/v1/watch/namespaces/myproject/deploymentconfigs', contentType: "application/json") { resp, reader ->
println(resp)
return reader
}
} catch (HttpResponseException e) {
System.out.println(e)
}
Please Advise on a path forward to set up OpenShift watchers in my application.
An error message is never thrown. minishift logs -f are not providing any feedback either.
Also note that I have gotten this to work with the curl command, documented in the api
You can use the OKHttpClient to handle the http websocket upgrade protocol for you. Note legacy versions of minishift require the query parameter "access_token" when trying to make a websocket connection request
OkHttpClient client = new OkHttpClient();
def token = token
Request request = new Request.Builder()
.get()
.url("https://<<IP>>/oapi/v1/watch/namespaces/<<namespace>>/deploymentconfigs?watch=true&access_token=<<token>>")
.addHeader("Accept", "application/json")
.addHeader("Connection", "close")
.addHeader("Sec-WebSocket-Protocol",'base64url.bearer.authorization.k8s.io.' + Base64.getEncoder().encodeToString(token.getBytes()))
.addHeader('Origin', 'https://<<IP>>')
.build()
WebSocketListener websocketListener= new WebSocketListenerImpl()
client.newWebSocket(request, websocketListener)
WebSocketListenerImpl Class
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;
public class WebSocketListenerImpl extends WebSocketListener {
public WebSocketListenerImpl() {
super();
}
#Override
public void onOpen(WebSocket webSocket, Response response) {
super.onOpen(webSocket, response);
print "WEBSOCKET OPEN"
}
#Override
public void onMessage(WebSocket webSocket, String text) {
super.onMessage(webSocket, text);
print "WEBSOCKET RECEIVED"
}
#Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
super.onMessage(webSocket, bytes);
print "WEBSOCKET OPEN"
}
#Override
public void onClosing(WebSocket webSocket, int code, String reason) {
super.onClosing(webSocket, code, reason);
print "WEBSOCKET CLOSING"
}
#Override
public void onClosed(WebSocket webSocket, int code, String reason) {
super.onClosed(webSocket, code, reason);
print "WEBSOCKET CLOSED"
}
#Override
public void onFailure(WebSocket webSocket, Throwable t, #javax.annotation.Nullable Response response) {
super.onFailure(webSocket, t, response);
println "WEBSOCKET FAILED"
}
}
Might be a dumb question but how can I retrieve the value of the response given by the RequestBuilder in a JSON format. My code is this:
try {
Request request = builder.sendRequest(json, new RequestCallback() {
public void onError(Request request, Throwable exception) {
System.out.println("CAN'T CONNECT");
// Couldn't connect to server (could be timeout, SOP violation, etc.)
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
System.out.println("SUCCESS");
System.out.println(response.getText());
// Process the response in response.getText()
} else {
System.out.println("ERROR" + response.getStatusCode() + response.getText());
// Handle the error. Can get the status text from response.getStatusText()
}
}
});
} catch (RequestException e) {
System.out.println(e);
}
Currently, the response gives me {faceAmount: 29921}. How do I access the value for faceAmount and store it to a variable? Is the response providing me with a JSON format or just straight up text string?
You can use com.google.gwt.json.client, or use JSNI and overlay types, or better, use JsInterop. You'll find more in the docs: http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsJSON.html, http://www.gwtproject.org/doc/latest/tutorial/JSON.html, http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsJsInterop.html
#JsType(isNative=true)
interface Response {
#JsProperty int getFaceAmount();
}
Response r = (Response) (JavaScriptObject) JsonUtils.parse(json);
I am using deferredResult on Spring MVC, but using this code, the timeout still are sending back the HTTP code 503 to the client.
future.onCompletion(new Runnable() {
#Override
public void run() {
if(future.isSetOrExpired()){
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
}
});
Any idea what else to try?
I ran into the same issue. My Spring MVC Controller method originally returned DeferredResult<Object>, but then I realised I wanted to control the HTTP status code. I found the answer here:
https://www.jayway.com/2014/09/09/asynchronous-spring-service/
#RequestMapping("/async")
DeferredResult<ResponseEntity<?>> async(#RequestParam("q") String query) {
DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>();
ListenableFuture<RepoListDto> repositoryListDto = repoListService.search(query);
repositoryListDto.addCallback(
new ListenableFutureCallback<RepoListDto>() {
#Override
public void onSuccess(RepoListDto result) {
ResponseEntity<RepoListDto> responseEntity =
new ResponseEntity<>(result, HttpStatus.OK);
deferredResult.setResult(responseEntity);
}
#Override
public void onFailure(Throwable t) {
log.error("Failed to fetch result from remote service", t);
ResponseEntity<Void> responseEntity =
new ResponseEntity<>(HttpStatus.SERVICE_UNAVAILABLE);
deferredResult.setResult(responseEntity);
}
}
);
return deferredResult;
}
Just use DeferredResult<ResponseEntity> and you can set both the response and the Http response code in the ResponseEntity.
I'm using GWT 2.3 and I have json-p requests in my code similar to this:
JsonpRequestBuilder jsonp = new JsonpRequestBuilder();
jsonp.requestObject(jsonUrl, new AsyncCallback<T>() {
public void onFailure(Throwable throwable) { // error }
public void onSuccess(T t) { //do something }
});
some GET-requests return 200, others 302 and so on, and I should be
able to return a different "answer" respect to this value. How can I
know what's the response value returned?
I think you can not access the response code using the JsonpRequestBuilder. But if you use the standard RequestBuilder instead you can get the response code using getStatusCode(). Of course you have to then the parse the response text yourself.
RequestBuilder r = new RequestBuilder(RequestBuilder.GET, jsonUrl);
r.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
// error
}
public void onResponseReceived(Request request, Response response) {
if (response.getStatusCode() == 200) {
//do something
} else if (response.getStatusCode() == 302) {
//do something else
}
}
});