How to set Request Body parameter in rest api - java

I have api using curl
curl -X PUT "http://localhost:8080/kie-server/services/rest/server/containers/containerid/tasks/210/expiration" -H "accept: application/json" -H "content-type: application/json" -d "{ \"java.util.Date\" : 1540025263987}"
Now I want to call this api using java code :
I am using javax.ws.rs.PUT class for api calling and HttpConnection class.
I have set the requestMethod(POST) and request property.
This is url i am using :
http://localhost:8080/kie-server/services/rest/server/containers/"+containerId+"/tasks/"+taskId+"/expiration
url = new URL( http://localhost:8080/kie-server/services/rest/server/containers/"+containerId+"/tasks/"+taskId+"/expiration);
conn.setRequestMethod(PUT);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json");
I want to pass this parameter to api but not sure which method to use ?
{java.util.Date:1534343434"};
This parameter is passed in body.
Can anyone suggest how do I pass this parameter in java rest api ??

Related

How to convert the below curl command in Java using HttpURLConnection?

How to convert the below curl command to Java using HttpURLConnection?
curl -D- -X GET -H "Authorization: Basic ZnJlZDpmcmVk" -H "Content-Type: application/json" "https://example.com:8081/rest/api/2/issue/QA-31"
How to set headers:
HttpURLConnection myCon = (HttpURLConnection) new URL("https://example.com:8081/rest/api/2/issue/QA-31").openConnection();
myCon.setRequestMethod("GET");
myCon.setRequestProperty("Content-Type","application/json");
myCon.setRequestProperty("Authorization", "Basic ZnJlZDpmcmVk");
After that you can read URL content in two ways
a. you can get InputStream from Connection as
InputStream inStream = myCon.getInputStream();
and read it as you want directly or with some reader etc.
b. by getting Content as
Object content = myCon.getContent();
For details read Java Docs for those methods it is very well documented.
BTW: keep in mind you have an SSL connection then you have to have remote server certificate in your java Key Store.

Java REST API that uses OpenAM token to determine user?

I am having trouble being able to validate a users token with OpenAM. Particularly what type of Agent I should create. Is there anyone that can recommend a solution?
Essentially the REST API will read the users OpenAM tokenid and validate the token with OpenAM which then will return data which contains a username. That username can be used in the REST API method to identify who is accessing the method.
Even more simplified is how can I use a OpenAM token to get the OpenAM user info.
Thanks!
You can use the following endpoints:
Authenticate user:
curl --request POST --header "X-OpenAM-Username: demo" \
--header "X-OpenAM-Password: changeit" \
--header "Content-Type: application/json"
"http://openam.example.com:8080/sso/json/authenticate"
{"tokenId":"AQIC5wM2LY4SfcyTReB5nbrLt3QaH-7GhPuU2-uK2k5tJsA.*AAJTSQACMDEAAlNLABMyOTUxODgxODAwOTE0MTA4NDE3*","successUrl":"/sso/console"}
Validate token:
curl --request POST \
--header "Content-Type: application/json" \
"http://openam.example.com:8080/sso/json/sessions/AQIC5wM2LY4SfczadxSebQWi9UEyd2ZDnz_io0Pe6NDgMhY.*AAJTSQACMDEAAlNLABM3MTMzMTYwMzM1NjE4NTE4NTMx*?_action=validate"
{"valid":true,"uid":"demo","realm":"/"}
Get profile attributes:
curl --request GET \
--header "iPlanetDirectoryPro: AQIC5wM2LY4SfczadxSebQWi9UEyd2ZDnz_io0Pe6NDgMhY.*AAJTSQACMDEAAlNLABM3MTMzMTYwMzM1NjE4NTE4NTMx*" \
"http://openam.example.com:8080/sso/json/users/demo"
{"username":"demo","realm":"/","uid":["demo"],"userPassword":["{SSHA}cIgTNGHWd4t4Ff3SHa6a9pjMyn/Z3e3EOp5mrA=="],"sn":["demo"],"createTimestamp":["20160406210602Z"],"cn":["demo"],"givenName":["demo"],"inetUserStatus":["Active"],"dn":["uid=demo,ou=people,dc=example,dc=com"],"objectClass":["devicePrintProfilesContainer","person","sunIdentityServerLibertyPPService","inetorgperson","sunFederationManagerDataStore","iPlanetPreferences","iplanet-am-auth-configuration-service","organizationalperson","sunFMSAML2NameIdentifier","oathUser","inetuser","forgerock-am-dashboard-service","iplanet-am-managed-person","iplanet-am-user-service","sunAMAuthAccountLockout","top"],"universalid":["id=demo,ou=user,dc=openamcfg,dc=example,dc=com"]}
I ended up going with with idFromSession:
curl --request POST \
--header "iplanetdirectorypro: AQIC5wM2LY4SfczUFNs-TJwFrCVAKgR0NulIAyNaIkQmjis.*AAJTSQACMDEA
AlNLABQtNTQ3NDE2Njc5ODk4MjYzMzA2MQ..*" \
--header "Content-Type: application/json"
http://openam.example.com:8080/openam/json/users?_action=idFromSession
Then in my java REST API method I used:
String httpsURL = "https://openam.example.com:8080/openam/json/users?_action=idFromSession";
URL url = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
//add request headers
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/json");
// Add session token as header
con.setRequestProperty("iplanetdirectorypro", "AQIC5wM2LY4SfczUFNs-TJwFrCVAKgR0NulIAyNaIkQmjis.*AAJTSQACMDEA
AlNLABQtNTQ3NDE2Njc5ODk4MjYzMzA2MQ..*");
// Send post request
con.setDoOutput(true);
// Read output
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
Based the HTTP POST off of: https://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/
don't you need cookies to be set ..
Response fieldResponse = given().auth().oauth2( oAuthLogin.getToken())
.config(new RestAssuredConfig().
decoderConfig(
new DecoderConfig("UTF-8")
).encoderConfig(
new EncoderConfig("UTF-8", "UTF-8")
))
.header("iplanetDirectoryPro", oAuthLogin.getToken())
.header("Content-Type", "application/json")
// .contentType("application/json")
.body(myRequest).with()
.when()
.post(dataPostUrl)
.then()
.assertThat()
.log().ifError()
.statusCode(200)
.extract().response();
is failing as bad request 400.Same content header is working in postman.
Only difference i see is cookie.enter image description here
Working as per postman
Not working one which used restassured framework enter image description here

How to send -u data of Curl in Rest client

I have a Curl request like:
curl -u "key:value" -H "headers" https://example.com
So, when I try to create a Rest client using this curl request in Java I am confused where to send the -u data in my request. Do we need to send it in Header or as URL parameter. Can somebody help me and tell me how can I send this -u in my Java code?
This is the code I am using:
URL url = new URL("https://example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Headers", "Value");
***conn.setRequestProperty("u", "key:Value");***
The header Authorization: Basic base64encoded(user:pass) works for this question.

Spring REST controller post request

I have this controller in spring
#RestController
public class GreetingController {
#RequestMapping(value = "/greeting", method = RequestMethod.POST)
public String greeting(#RequestParam("uouo") String uouo) {
return uouo;
}
}
and when I testing it
curl -k -i -X POST -H "Content-Type:application/json" -d uouo=test http://192.168.1.104:8080/api/greeting
the result of the testing
HTTP Status 400 - Required String parameter 'uouo' is not present
I tried may thing, but I think #RequestParam can't use for POST it always passed the parameter in URL using GET, I use post only if I had object JSON as parameter using #RequestBody, is there any way to make string parameter send using POST?
The Servlet container will only provide parameters from the body for POST requests if the content type is application/x-www-form-urlencoded. It will ignore the body if the content type is anything else. This is specified in the Servlet Specification Chapter 3.1.1 When Parameters Are Available
The following are the conditions that must be met before post form
data will be populated to the parameter set:
The request is an HTTP or HTTPS request.
The HTTP method is POST.
The content type is application/x-www-form-urlencoded.
The servlet has made an initial call of any of the getParameter family of methods on the request object.
If the conditions are not met and the post form data is not included
in the parameter set, the post data must still be available to the
servlet via the request object’s input stream. If the conditions are
met, post form data will no longer be available for reading directly
from the request object’s input stream.
Since you aren't sending any JSON, just set the appropriate content type
curl -k -i -X POST -H "Content-Type:application/x-www-form-urlencoded" -d uouo=test http://192.168.1.104:8080/api/greeting
or let curl infer it
curl -k -i -X POST -d uouo=test http://192.168.1.104:8080/api/greeting?uouo=test
Note that you can still pass query parameters in the URL
curl -k -i -X POST -H "Content-Type:application/json" http://192.168.1.104:8080/api/greeting?uouo=test

Curl oAuth equivalent in Java

I can't find the way to reproduce the following curl oAuth authentication call in Java:
curl 'https://id.herokuapp.com/oauth/token' -H 'Content-Type: application/x-www-form-urlencoded' -H 'Accept: application/json' -H 'Authorization: Basic AUTH_VALUE' -H 'Connection: keep-alive' --data 'username=_USERNAME&password=_PASSWORD&grant_type=password&scope=read%20write&client_secret=_SECRET&client_id=_CLIENT_ID' --compressed
I don't know how to pass the --data value to the call.
If you're using standard java.net.URL it can be done but the syntax is rather cumbersome, I suggest that you try using HTTP Components library. You should end up with something like this:
final HttpUriRequest request = RequestBuilder.get()
.setUri("https://id.herokuapp.com/oauth/token")
.setHeader("Content-Type", "application/x-www-form-urlencoded")
.setHeader("Accept", "application/json")
.setHeader("Authorization", "Basic AUTH_VALUE")
.addParameter("username", "_USERNAME")
.addParameter("password", "_PASSWORD")
.addParameter("grant_type", "password")
.addParameter("scope", "read write")
.addParameter("client_secret", "_SECRET")
.addParameter("client_id", "_CLIENT_ID")
.build();
final HttpClient client = HttpClientBuilder.create().build();
final HttpResponse response = client.execute(request);
final HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.toString(entity)); // or whatever processing you need
GZip/deflate and keep alive handling is provided out of the box if the HttpClient is created using HttpClientBuilder.

Categories

Resources