Hi I'm very new to Swift and trying to make a simple application.
I'm using 'alamofire 5 beta 6' to make a request.
Here is some code below
-code for making post request
var json:JSON = JSON(["id":id.text, "password":enteredPassword])
var parameters: Parameters = ["id":id.text, "password":enteredPassword]
let headers:HTTPHeaders = [ "Content-Type":"application/json"]
AF.request("http://127.0.0.1:8080/user", method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: headers).responseJSON{
response in
print("response : \(response)")
}
-code for Spring Framework
#RequestMapping(value="user", method=RequestMethod.POST)
public JSONObject addUser(
#RequestBody Memberinfo member,
HttpServletRequest request) {
JSONObject result = new JSONObject();
return result;
}
-Memberinfo.java that is used in controller to retrieve #RequestBody
public class Memberinfo {
String id;
String password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
In Swift code, I set parameter id and password to retrieve it back in Spring framework.
However, right after I make a request, Alamofire responses with message
response : success({
error = "Bad Request";
message = "JSON parse error: Unrecognized token 'id': was expecting ('true', 'false' or 'null'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'id': was expecting ('true', 'false' or 'null')\n at [Source: (PushbackInputStream); line: 1, column: 4]";
path = "/user";
status = 400;
timestamp = "2019-06-09T05:46:07.417+0000";
})
I think the parameter should be sent as following
var parameters: Parameters = {"id":id.text, "password":enteredPassword}
Another important thing that you don't need to have a JSONObject as a response type for your endpoint you can just annotate your endpoint with #ReponseBody to have a json response
#RequestMapping(value="user", method=RequestMethod.POST)
#ResponseBody
public ResponseEntity<JSONObject> addUser(
#RequestBody Memberinfo member,
HttpServletRequest request) {
JSONObject result = new JSONObject();
return result;
}
Always use something like Postman or RestClient to test your endpoint before calling this endpoint from an external source
Related
Here's my front-end code:
// the img64 here does received data from client with a long char sequence
console.log(img64);
axios.post(serverUrl + '/adminMng/adminFaceLogin',
{
username: username,
img64: img64
})
.then(res => {
console.log(res.data);
if (res.data.status == 200) {
alert("Face recognition successful! Click to confirm to enter the system");
window.location = app.adminIndexUrl;
} else {
alert(res.data.msg);
}
});
And the AdminLoginBO is :
public class AdminLoginBO {
private String username;
private String password;
private String image64;
// getter and setter
...
}
The AdminMngControllerApi is
#RequestMapping("/adminMng")
public interface AdminMngControllerApi {
#PostMapping("/adminFaceLogin")
GraceJSONResult adminFaceLogin(#RequestBody AdminLoginBO adminLoginBO,
HttpServletRequest request,
HttpServletResponse response);
}
And the implementing class of AdinMngControllerApi is:
#RestController
public class AdminMngController implements AdminMngControllerApi {
#Override
public GraceJSONResult adminFaceLogin(AdminLoginBO adminLoginBO, HttpServletRequest request,
HttpServletResponse response) {
String username = adminLoginBO.getUsername(); // this value is valid, eg: "andrew"
String image64 = adminLoginBO.getImage64(); // but this value is null
//face login logics
...
}
}
Both the params from front-end received valid value from client, but when it goes into backend, the "username" variable received the value, but the "img64" variable is null.
That's because the name of the object sent at the front end is img64, and the AdminLoginBO expects a image64 as a name. For the username, both of the object matches the name.
You can change img64: img64 for image64: img64
I am in the process of studying Rest-Assured framework.
I am using http://ziptasticapi.com free API for my drills.
When I call:
final static String BASE_URI = "http://ziptasticapi.com/";
final static String ADAK_ZIP_CODE = "99546"; //{"country":"US","state":"AK","city":"ADAK"}
final static String ATKA_ZIP_CODE = "99547";
public static final String GET_METHOD = "GET";
RestAssured.baseURI = BASE_URI;
String responseString = when().get(ADAK_ZIP_CODE).then()
.statusCode(200)
.and()
.extract()
.asString();
System.out.println(responseString);
I get the following string:
{"country":"US","state":"AK","city":"ADAK"}
as responseString value.
When I am trying:
RestAssured.baseURI = BASE_URI;
ZipData zipdata = when().get(ADAK_ZIP_CODE).then()
.statusCode(200)
.and()
.extract()
.as(ZipData.class);
public class ZipData {
public String country;
public String state;
public String city;
}
I crash on :
java.lang.IllegalStateException: Cannot parse object because no
supported Content-Type was specified in response. Content-Type was
'text/html;charset=UTF-8'.
Why is that? Could it be the rest returns an Html and not Json? How do I handle this?
Thanks!
First of all, keep in mind that REST Assured is a HTTP client primarily designed for testing HTTP APIs. So let me highlight that you shouldn't use REST Assured for anything other than testing.
Looks like the endpoint you are attempting to consume is returning a JSON document in the response payload, but the value of the Content-Type header is text/html;charset=UTF-8, so REST Assured cannot parse the response as a JSON document and convert it to an instance of ZipData. That's not what you expect from a sound HTTP API.
You could work around it and write a filter to override the Content-Type header, as show below:
public class OverrideContentTypeFilter implements Filter {
#Override
public Response filter(FilterableRequestSpecification requestSpec,
FilterableResponseSpecification responseSpec,
FilterContext ctx) {
Response next = ctx.next(requestSpec, responseSpec);
return new ResponseBuilder().clone(next).setContentType(ContentType.JSON).build();
}
}
Then use it as follows:
ZipData zipdata =
given()
.filter(new OverrideContentTypeFilter())
.when()
.get(uri)
.then()
.statusCode(200)
.extract()
.as(ZipData.class);
I am new to REST. I have written a small REST resource and Whenever I try to invoke the REST service from POSTMAN, i get a empty response {} and status code 200
The Request :
http://localhost:8080/demo/managers
#GET
#Path("managers")
#Produces({"application/json"})
public Response getManagers() throws GeneralException, JSONException
{
JSONArray valueString = COMING_FROM_OTHER_METHOD();
System.out.println("==== "+valueString.toString());
return Response.ok(valueString,MediaType.APPLICATION_JSON).build();
}
The correct value I can see in System.out.println():
[{"display":"john","id":"003"},{"display":"hansi","id":"004"},{"display":"samy gayle","id":"005"}]
I want to a JSONArray Response but everytime I get an empty response
{}
But when modify the code like below it gives correct response
#GET
#Path("managers")
#Produces({"application/json"})
public String getManagers() throws GeneralException, JSONException
{
JSONArray valueString = COMING_FROM_OTHER_METHOD();
System.out.println("==== "+valueString.toString());
return valueString.toString();
}
Kindly Help. why am I getting {} when trying to return a Response object J
I would use domain objects rather than String instances:
class Manager {
private String id;
private String display;
... setters/getters ...
}
public ResponseEntity<ArrayList<Manager>> getManagers() throws GeneralException {
ArrayList<Manager> managers = COMING_FROM_OTHER_METHOD();
return new ResponseEntity<>(managers, HttpStatus.OK);
}
I am calling sample google book URL from the lightning component, For that i have written APEX controller to make http request . But it is throwing 404 error for the Google Book API. Here is my APEX controller please check ,
public class WebservicesController {
public static String responseFormat='application/json';
public static String bodyContentType='application/json';
#AuraEnabled
public static Response makeRequest(String url, String method, String bodyContent) {
System.debug('Making request httpResponse ' );
HttpRequest request = buildRequest(url, method,bodyContent);
HttpResponse httpRes = sendRequest(request);
Response restRes = buildResponse(httpRes);
return restRes;
}
private static HttpRequest buildRequest(String url, String method, String bodyContent) {
HttpRequest request = new HttpRequest();
System.debug('Making request httpResponse '+ url );
request.setEndpoint(url);
request.setMethod(method);
request.setHeader('Content-Security-Policy', '*');
if (bodyContent != null) {
request.setBody(bodyContent);
request.setHeader('Content-Type', bodyContentType);
}
request.setHeader('ACCEPT', responseFormat);
return request;
}
private static HttpResponse sendRequest(HttpRequest request) {
return new Http().send(request);
}
private static Response buildResponse(HttpResponse httpRes) {
Response restRes = new Response();
restRes.status = httpRes.getStatus();
restRes.statusCode = httpRes.getStatusCode();
restRes.body = httpRes.getBody();
System.debug(' Status code is ' + restRes.statusCode );
System.debug(' httpResponse ' + httpRes.getBody() );
return restRes;
}
public class Response {
#AuraEnabled
public String status { get; set; }
#AuraEnabled
public Integer statusCode { get; set; }
#AuraEnabled
public String body { get; set; }
}
}
and also my helper js controller where i am calling this apex controller is method is below ..
createCustomer: function(component, customer) {
var action = component.get("c.makeRequest");
action.setParams({
url: "https://www.googleapis.com/books/v1/volumes/NFPqCQAAQBAJ",
method: "GET",
bodyContent: "",
});
action.setCallback(this, function(a) {
action.setCallback(this, function(response){
var state = response.getState();
if (state === "SUCCESS") {
var customers = component.get("v.data");
customers.push(response.getReturnValue());
component.set("v.data", customers);
}
var action = component.get("c.saveCustomer");
action.setParams({
"customer": customer
});
});
$A.enqueueAction(action);
});
$A.enqueueAction(action);
},
And i also given this google api url in Remote settings and also added as CSP trusted site in my domain.
Add #AuraEnabled in front of following method:
buildRequest
sendRequest
buildResponse
My server code is as:
#POST
#Path("/getMapping")
public ListResponse getMapping(Long id, String name, String clientName, String instanceName) {
ListResponse response = null;
try {
response = new ListResponse();
List<Mappings> mappings = service.getMapping(id, name, clientName, instanceName);
response.setStatusCode(SUCCESS);
response.setMappings(mappings);
} catch (Exception e) {
setResponseErrors(response, e);
}
return response;
}
I am using Jersey REST client, but I dont think there is an option to have multiple params passed in the post method like:
ClientResponse clientResponse = webResource.type(XML_TYPE).post(ClientResponse.class, id, name, clientName, instanceName);
Is there a way to accomplish this?
I could use MultiValuedMap or #QueryParams in this case, but there are other cases where multiple params are more complex Objects. Also, wrapping all in a "paramContainer" will be an inefficient solution since there are so many such methods with multiple params with different combinations.
(As an aside, why would REST not support multiple params?)
Any help greatly appreciated.
here is how I'll do it
SERVER CODE
1.1 should have to use #FormParam in order to declare parameters in #FormDataParam
1.2 a POST is better if encrypted for that use #Consumes(MediaType.MULTIPART_FORM_DATA)
you will have a server code like this :
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Path("/getMapping")
public ListResponse getMapping(#FormParam("id")Long id, #FormParam("name") String name, #FormParam("clientName") String clientName, #FormParam("instanceName") String instanceName) {
ListResponse response = null;
try {
response = new ListResponse();
List<Mappings> mappings = service.getMapping(id, name, clientName, instanceName);
response.setStatusCode(SUCCESS);
response.setMappings(mappings);
} catch (Exception e) {
setResponseErrors(response, e);
}
return response;
}
CLIENT CODE
Form form = new Form();
form.add("id", "1");
form.add("name", "je#rizze.com");
form.add("clientName","firefox");
form.add("instanceName","node45343.rizze.com");
ClientResponse response = webResource
.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.post(ClientResponse.class, form);
enjoy :)
An addition to jeorfevre's answer above:
In case you're using Jersey 1.x, this is how it works:
Client: (pure Java):
public Response testPost(String param1, String param2) {
// Build the request string in this format:
// String request = "param1=1¶m2=2";
String request = "param1=" + param1+ "¶m2=" + param2;
WebClient client = WebClient.create(...);
return client.path(CONTROLLER_BASE_URI + "/test")
.post(request);
}
Server:
#Path("/test")
#POST
#Produces(MediaType.APPLICATION_JSON)
public void test(#FormParam("param1") String param1, #FormParam("param2") String param2) {
...
}