Reputation: 59
I have been struggling with this for the past couple days and I think I tried every example I could find on the internet. I'm trying to sign in to my REST and get back the Authorization code for ongoing communication. It works when using Postman
----Taken from Postman Generate Code Snippit----
POST /api/auth/signin HTTP/1.1
Host: localhost:5000
Content-Type: application/json
cache-control: no-cache
Postman-Token: baffa067-c2a0-4d5c-b321-348682227195
{
"username": "Test",
"password": "Testpw"
}------WebKitFormBoundary7MA4YWxkTrZu0gW--
and it returns
{"accessToken":"eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxIiwiaWF0IjoxNTQ0Mjc4MTE5LCJleHAiOjE1NDQ4ODI5MTl9.qNQ7MIIsWpYQdeje6Ox88KR9AdNGCSiffjyk__nrdWvP7yoy4Ukk05ZQUISVptOIoBpahFT1OHf_MXVQnW5Izg","tokenType":"Bearer"}
My code in my CodenameOne project is:
public void onloginActionEvent(com.codename1.ui.events.ActionEvent ev) {
JSONObject json = new JSONObject();
try {
ConnectionRequest post = new ConnectionRequest(){
@Override
protected void buildRequestBody(OutputStream os) throws IOException {
os.write(json.toString().getBytes("UTF-8"));
}
@Override
protected void readResponse(InputStream input) throws IOException {
}
@Override
protected void postResponse() {
}
};
json.put("username", "Test");
json.put("password", "Testpw");
post.setUrl("http://localhost:5000/api/auth/signin");
post.setPost(true);
post.setContentType("application/json");
post.addArgument("body", json.toString());
String bodyToString = json.toString();
NetworkManager.getInstance().addToQueueAndWait(post);
Map<String,Object> result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(post.getResponseData()), "UTF-8"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
When using the CodenameOne Simulator Network Monitor has the following result
URL: http://localhost:5000/api/auth/signin
Type: Post
Request:BodyPart: {"password":"Test","username":"Testpw"}
Request:Request Headers: User-Agent=[Mozilla/5.0 (Linux; U; Android 2.2; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1]
Content-Type=[application/json]
Response:Body: blank
Response: Response Headers: Transfer-Encoding=[chunked]
X-Frame-Options=[DENY]
null=[HTTP/1.1 200]
Cache-Control=[no-cache, no-store, max-age=0, must-revalidate]
X-Content-Type-Options=[nosniff]
Expires=[0]
Pragma=[no-cache]
X-XSS-Protection=[1; mode=block]
Date=[Sat, 08 Dec 2018 14:14:54 GMT]
Content-Type=[application/json;charset=UTF-8]
Upvotes: 1
Views: 207
Reputation: 52770
You override readResponse
without calling super
. This overrides the default behavior of reading the data. You can just remove that method or write the logic for reading the JSON within that method.
Upvotes: 1