How to request Rest API eclipse service in postman? - java

I generate this Rest API service in java eclipse, now i am not sure how to test this in Postman.
So can anyone guide me on how the #QueryParam json object will be written in postman?
#Path("/UpdateTenantProfile")
public class UpdateTenantProfile {
#SuppressWarnings({ "unchecked" })
#POST
#Path("UpdateTenantProfiledetails")
#Produces("application/json")
#Consumes("application/json")
public String UpdateTenantProfilem(#QueryParam("profileDetail") JSONObject profileDetail) throws JSONException {
Connection dbConnection = null;
Statement stmt = null;
JSONObject jsarr = new JSONObject();
try {
// con.setAutoCommit(false);
dbConnection = DBConnection.getDBConnection();
dbConnection.setAutoCommit(false);
stmt = (Statement) dbConnection.createStatement();
// System.out.println("Iam entering try catch bloxck");
// System.out.println("length of json data"+kcm.length());
String PIDNO = profileDetail.getString("PIDNO");
String GENDER = profileDetail.getString("GENDER");
String TENANTNAME = profileDetail.getString("TENANTNAME");
String EMAIL = profileDetail.getString("EMAIL");
String OFFPHONE = profileDetail.getString("OFFPHONE");
String MOBILE = profileDetail.getString("MOBILE");
Either it's inside url, body or form data I don't have idea about it,

You can give encoded Query Param in the Postman Inside Params tab near Auth Tab as shown below.
You can do encoding of data from https://www.url-encode-decode.com/
Edit :
As you can see I got a perfect response from API. I returned the Value of JSON from API.

Related

HTTP POST from Java with JSON issue

Could anyone advise on why this code would not work for a HTTP Post with JSON? No response is received.
I am using Java in Android Studio - using the emulator on my laptop and want to access localhost on my laptop (so using 10.0.2.2).
Then want to take the JSON response, set this as a string just to test I am getting a response.
String jsonResponse = "No response received";
try {
//where write JSON with account details etc
JSONObject json = new JSONObject();
json.put("accountID", "test");
URL url = new URL("http://10.0.2.2:8082/queryTransaction");
HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
httpcon.setDoOutput(true);
httpcon.setRequestMethod("POST");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
OutputStreamWriter output = new OutputStreamWriter(httpcon.getOutputStream());
output.write(json.toString());
httpcon.connect();
jsonResponse = httpcon.getResponseMessage();//json response from API
}catch(Exception e){
}
Edit: I get this error which I have now found...
Method threw 'java.lang.NullPointerException' exception. Cannot evaluate com.android.okhttp.HttpUrl$Builder.toString()
so there are a few caveats with this. I got this working after making a few changes.
Make sure to set the charset.
setRequestProperty("charset", "utf-8");
Dont wrap the OutputStream, put it in a try-with-resources, and write the json as a byte array as utf-8 since that what we're accepting.
try (OutputStream output = httpcon.getOutputStream()) {
output.write(json.toString().getBytes(StandardCharsets.UTF_8));
}
Make sure your Json object is correct. If you're going to use accountID make sure you're consuming it properly. Gson/Jackson for example won't be able to parse this as conventionally it would accept account_id or accountId. Use #JsonProperty if needed.
#JsonProperty("account_id")
private final String accountId;
Example Controller with Spring Boot
#RestController
public class TestPostController {
public static class Account {
#JsonProperty("account_id")
private final String accountId;
public Account(String accountId) {
this.accountId = accountId;
}
public Account() {
this(null);
}
public String getAccountId() {
return accountId;
}
}
#PostMapping(path = "/test-post", consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Account> response(#RequestBody Account account) {
return ResponseEntity.ok(account);
}
}

add alert in body of java jersey application

for a project I'm developing an app with web services
My problem concerns the login page, that is when I manage that the user has not registered, I would like to show an alert on the same login page..
#Path("postlogincookie")
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response postLoginAdminCookie(#FormParam("username") String username, #FormParam("password") String password)
{
java.sql.Connection con = null;
SqliteConnection sqlite = new SqliteConnection();
sqlite.setDbPath(dbPath);
con = sqlite.connect();
String query = "SELECT Username,Password,Role FROM User WHERE Username ='"+username+"' and Password='"+password+"'";
ResultSet rs = con.createStatement().executeQuery(query);
if(!rs.next())
{
return Response.status(Response.Status.UNAUTHORIZED).entity("Non sei registrato, registrati!").build();
}
currently I use return Response.status(Response.Status.UNAUTHORIZED).entity("Non sei registrato, registrati!").build(); but I don't want to change page to give the error message.
is there a solution to give a message of alert or error on login page?

web service in spring getParameter

I am creating a web service, but I am not getting the value I expect by using req.getParameter("key"). Can you please tell why I am getting values as null ?
Here, instead of getting "abcd" as value, I am getting null.
The request which I am hitting is:
http://localhost:8080/api.htm.
Post fields are:
username:abcd
#ResponseBody
#RequestMapping(value = {"api"}, method = {RequestMethod.POST})
public String apiSignUp(HttpServletRequest req) throws JSONException {
JSONObject json = new JSONObject();
Users user;
try {
String username = req.getParameter("username");

Change URL pattern of rest API

#Path("/ftocservice")
public class RestService {
#Path("{f}")
#GET
#Produces("application/json")
public Response convertFtoCfromInput(#PathParam("f") float f)
throws Exception {
DbCon db = new DbCon();
ArrayList<Student> students = db.getStudentList();
JSONArray jsonArray = new JSONArray(students);
String result = jsonArray.toString();
return Response.status(200).entity(result).build();
}
}
I'm using above source code to generate rest API and user is requesting through the API as follows.
http://localhost:8080/RestExample/RestService/ftocservice/23
I need to change the request URL as follows.
http://localhost:8080/RestExample/RestService/ftocservice?f=23
Please help to change the source code to change request URL as given. Thanks
Change to use #QueryParam instead:
#Path("/ftocservice")
public class RestService {
#GET
#Produces("application/json")
public Response convertFtoCfromInput(#QueryParam("f") float f)
throws Exception {
DbCon db = new DbCon();
ArrayList<Student> students = db.getStudentList();
JSONArray jsonArray = new JSONArray(students);
String result = jsonArray.toString();
return Response.status(200).entity(result).build();
}
}
See this link for more info on parameter types in JAX-RS.
This tutorial by Mkyong.com is also quite nice.
use #QueryParam instead of #PathParam

JSON Object as #RequestBody on Spring 4.16

So i have this android application that send jsonObject for a jsonObjectRequest (I'm using volley) with POST method. The JSON file was sent but the server (this is where i'm using Spring btw) is not responding. The code pretty much like these.
Android Code:
JSONObject jsonObject = new JSONObject(data);
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
userToken = response.getString(TAG_TOKEN);
// blablabla
Server Code:
#RestController
#RequestMapping("/auth/")
public class AuthController {
String userEmail;
String userPassword;
#RequestMapping(value = "/login", method = RequestMethod.POST)
public LoginResponse loginResponse(#RequestBody Auth auth){
userEmail = auth.getEmail();
userPassword = auth.getPassword();
// blablabla
Auth Object:
public class Auth {
private String email;
private String password;
// blablabla
It seems like the server didn't receive the JsonObject from the android client correctly. (The server is able to send JSON to android client perfectly in another case, though). I'm using spring-4.16, jackson-core, jackson-annotation, jackson-databind (2.2.2). Thanks in advance!
From the code you supplied first thing that I suspect can be is that JSONObject doesn't have same field's name with Auth on server.
Also it is possible that HttpMessageConverter which is used for mapping objects from request to object in controller is not doing his job correctly.
I would first try to just try to recieve parameters from body, without Auth object. If Spring maps it fine than HttpMessageConverter is the problem, if it does not than the usage of #RequestBody, which I can't be from code you supplied.

Categories

Resources