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);
Related
I have this JSON request framed in Java. I will be hitting a rest template with my URL and this request.
{
"searchRequest":{
"header":{
"agency":"1111",
"agent":"2222";
"from":"0";
"size":"15"
},
"requestParam":{
"firstName":"JOHN",
"lastName":"PAK",
"dob":"",
"driverLicense":"",
"membershipNumber":"",
"phoneNumbers": "null",
"addresses":"null"
}
}
}
CASE 1: Whenever I get a successful response, I get the same JSON which my rest template gives in the response variable.
public #ResponseBody String mpdValidate(#RequestBody String inputRequest, #RequestHeader String url)
throws JsonParseException, JsonMappingException, IOException, JSONException {
System.out.println(inputRequest);
System.out.println(url);
String response = null;
if (url == null || url.isEmpty()) {
url = "myURL";
}
try {
HttpHeaders headers = new HttpHeaders();
headers.set("X-ApplicationContext",
"{\"userId\":\"user\",\"transactionType\":\"realtime\",\"application\":\"app\",\"subSystem\":\"mpd\",\"address\":\"1.0.0.0\",\"correlationId\":\"0f333c\"} ");
HttpEntity<String> request = new HttpEntity<String>(inputRequest, headers);
response = restTemplate.postForObject(url, request, String.class);
} catch (Exception e) {
response = e.getMessage();
}
return response;
}
CASE 2: And when there is a wrong request framed and there is a failed response, the rest template returns this response.
{
"httpCode": 400,
"httpMessage": "Bad Request",
"moreInformation": "Request parameter is null",
"timeStamp": 1539072063795
}
But the response variable returns null and enters to catch block throwing null pointer exception.
I want the above JSON in string format to my response variable.
Can someone help?
try {
// ...
} catch (HttpClientErrorException expection) {
response = expection.getResponseBodyAsString();
}
You need to handle HttpClientErrorException (or its parent RestClientResponseException) and extract the response by HttpClientErrorException#getResponseBodyAsString.
You should try like this,
// REST Request
try {
restTemplate.postForObject(requestUrl, postBody, Void.class);
} catch (RestException restException) {
Logger.error(this, "RestException: " + restException.getRestError().toString());
response = restException.getRestError().toString();
}
I'm writing some small android application that works with REST services.
The base structure of the response is:
{
result: "ok/error",
message: "some string",
entity: "either object or error description"
}
The entity type is different each time whether the response is ok or error.
Now, I'm calling the service from AsyncTask and I need to return the result to the UI thread.
I'm using gson library to desirialize the JSON from the server. The problem is that I do not have the ability to know what type of response I've got (ok or error).
Also, the AsyncTask can return only single type to the UI thread. Below is an example for what I could come up with. I need to state that I'm not a java programmer and I may not know all the patterns and maybe I miss something.
Anyway, I'll be glad for any help.
public class RegisterProxyAsync extends AsyncTask<User, String, Object> {
#Override
protected Object doInBackground(User... params) {
try {
Gson gson = new Gson();
String request = gson.toJson(params[0]);
HttpClient client = new DefaultHttpClient();
HttpPost postAction = new HttpPost("http://SomeServiceEndpoint/register");
postAction.addHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
postAction.setEntity(new StringEntity(request));
HttpResponse response = client.execute(postAction);
if (response != null) {
InputStream stream = response.getEntity().getContent();
String strResult = CharStreams.toString(new InputStreamReader(stream));
try {
UserResponse userResponse = gson.fromJson(strResult, UserResponse.class);
return userResponse;
} catch (Exception e) {
ErrorResponse errorResponse = gson.fromJson(strResult, ErrorResponse.class);
return errorResponse;
}
Log.e("debug", strResult);
}
} catch (Exception e) {
// TODO:Handle exception
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Object result) {
// TODO: execute some work
}
}
EDIT:
I've changed the server to return proper HttpCodes (200 for success, 400 for error) but, I still have the problem of returning two different types of object from the doinbackground method, one for error and another for success.
A proper REST service should include an HTTP response code indicating the status of the processed request. If you have control over the service then I would recommend altering it to return a variant of 40x or 50x codes, to signal that an error has occurred. The service should only return a 200 OK if the request succeeded. On your client side, you would then parse the response based on the status code (normal entity for 200 ok, error entity for anything else). Pseudocode:
if(response.getStatusLine().getStatusCode() == 200) {
UserResponse userResponse = gson.fromJson(strResult, UserResponse.class);
} else {
ErrorResponse errorResponse = gson.fromJson(strResult, ErrorResponse.class);
}
If you can't change the server side for whatever reason, then on your client side you will have to use a generic JsonObject to parse the response. Pseudocode:
JSONObject jsonObj = new JSONObject(strResult);
if("ok".equals(jsonObj.get("result")) {
return gson.fromJson(jsonObj.toString(), UserResponse.class);
} else {
return gson.fromJson(jsonObj.toString(), ErrorResponse.class);
}
I have two web applications hosted on a server. From one I am trying to do $.post to the second application (spring mvc3). I am able to successfully hit the url of the second application but I do not get response back of the ajax call.
App1 JS Code (http://localhost:7777/app1/test.html) -
var serialisedFormData = $("form").serialize();
$.post("http://localhost:8080/app2/doSomething", serialisedFormData, function (data) {
alert("job done");
}, "json");
App2 Java Code -
#RequestMapping(value = "/doSomething")
public #ResponseBody String doSomething(HttpServletRequest request,
#RequestParam("d") String data) {
try {
... do something here ...
return "done";
}
catch (Exception e) {
logger.debug("Exception occured when doing something", e);
return "failure";
}
}
I achieved it by removing "json" type from my jquery post call.
$.post("http://localhost:8080/app2/doSomething", serialisedFormData, function (data) {
alert("job done");
});
and adding a header to my response
#RequestMapping(value = "/doSomething")
public #ResponseBody String doSomething(HttpServletRequest request, HttpServletResponse response, #RequestParam("d") String data)
{
try {
... do something here ...
response.setHeader("Access-Control-Allow-Origin", "*");
return "done";
}
catch (Exception e) {
logger.debug("Exception occured when doing something", e);
return "failure";
}
}
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.
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
}
}
});