How to delete a webresponse based on jsessionId in c#? - java

I am trying to do API testing in c#. I have a webresponse with some values uploaded to a url and a WebClient object with some headers (JSESSIONID, path etc)
string cookie = JSESSIONID : ajyrnXWREThsarfoWSGGREGarevr;
myWebClient.Headers.Add(HttpRequestHeader.Cookie, cookie);
var responseArray1 = myWebClient.UploadValues(restURL, "POST", myQueryStringCollection2);
Now I want to delete the response with the above JSESSIONID.
I was able to do this in Java with the below code:
Client client = Client.create();
Builder webResource = client.resource(restUrl).cookie(cookie);
ClientResponse response1 = webResource.type("application/json").delete(ClientResponse.class);
Please let me know how to proceed in C#.

Related

415 error while calling post API from jersey client

I have below API which returns back the access_token.
POST https://idcs-xxxxxxxxxbf08128c3d93a19c.identity.c9dev2.oc9qadev.com/oauth2/v1/token
in header content-type is application/x-www-form-urlencoded. also in body it contains below parameter.
I send user name and password and it is secured with basic authentication. It provides access_token when I call from postman. also it provides output when I consume using HttpUrlConnection
url = new URL(tokenURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Authorization", auth);
connection.setRequestProperty("Accept", "application/json");
OutputStream os = connection.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write("grant_type=client_credentials&scope=" + scope);
The above code is working properly. But when I use jersey it gives 415 error. I am using below code.
String user="idcs-oda-zzzxxxxxf93560b94eb8a2e2a4c9aac9a3ff-t0_APPID";
String password="xxxxxxx-6f71-4af2-b5cc-9110890d1456";
String scope = "https://idcs-oda-xxxxxxxxxxxxxxxxe2a4c9aac9a3ff-t0.data.digitalassistant.oci.oc-test.com/api/v1";
String tokenURL = "https://idcs-xxxxxxxxxxxxxxxx28c3d93a19c.identity.c9dev2.oc9qadev.com/oauth2/v1/token";
HttpAuthenticationFeature feature= HttpAuthenticationFeature
.basicBuilder()
.nonPreemptive()
.credentials(user,password)
.build();
ClientConfig clientConfig = new ClientConfig();
clientConfig.register(feature);
Client client = ClientBuilder.newClient(clientConfig);
WebTarget webTarget= client.target(tokenURL);
PostDetails post= new PostDetails("client_credentials",scope); //Bean class to assign body parameter
Response response= webTarget.request()
.header("Content-Type", "application/x-www-form-urlencoded")
.post(Entity.json(post));
System.out.println(response);
Can somebody tell me what mistake I am doing in Response line.
You need to set your Accept on the request method:
Response response= webTarget.request(MediaType.APPLICATION_JSON)
.header("Content-Type", "application/x-www-form-urlencoded")
.post(Entity.json(post));
You also need to ensure that if your API accepts application/x-www-form-urlencoded content, that is what you are sending.
Currently, you are sending application/json content based on your usage of Entity.json(post).
I don't know what type is assigned to post, but you need to figure out how to convert it either to a Form or a MultiValuedMap<String,String>, and then use the form method on Entity to submit your content.
Response response= webTarget.request(MediaType.APPLICATION_JSON)
.header("Content-Type", "application/x-www-form-urlencoded")
.post(Entity.form(postForm)); //assuming postForm typed as Form or MultiValuedMap<String,String>
Taking a guess regarding post, creating postForm as a MultiValuedMap<String,String> may be as simple as the following (which you would place prior to your request, of course).
MultiValuedMap<String,String> postForm = new MultiValuedHashMap<>();
postForm.add("client_credentials",scope);
What you need is:
Response response= webTarget.request()
.accept("application/json") // Accept field from header of request
.header("Content-Type", "application/x-www-form-urlencoded") //manually set content-tyoe
.post(Entity.entity(input, MediaType.TEXT_PLAIN)); // request body
The best way to see what is Jersey actually is sending is to register logger, and log network. For example:
clientConfig.register(
new LoggingFeature(
new Slf4jLogger(this.getClass().getName(), null)));
where Slf4jLogger is from org.apache.cxf:cxf-core.

How do we consume rest api with Http basic authentication in spring?

I want to consume rest api from url with http basic authentication that returns a big json & then i want to parse that json without POJO to get some values out of it. How can i achieve that in java spring?
I know this is common question but i could not get proper solution that worked for me.
Please help me someone.
Using the Apache HttpClient, the following Client Code snipped has been copied from the following URL. The comments have been added by myself.
https://www.baeldung.com/httpclient-4-basic-authentication
HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
// Combine the user and password pair into the right format
String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
// Encode the user-password pair string in Base64
byte[] encodedAuth = Base64.encodeBase64(
auth.getBytes(StandardCharsets.ISO_8859_1));
// Build the header String "Basic [Base64 encoded String]"
String authHeader = "Basic " + new String(encodedAuth);
// Set the created header string as actual header in your request
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));

Jersey ClientResponse getCookies failing to parse correctly

I have some Java code which is calling a restful service, and needs to first authenticate and store cookies for a future call. I am using Jersey 1.8. The problem is that after making the call to authenticate, I try to retrieve the cookies using ClientResponse.getCookies() and iterate through the list of NewCookie objects. However, when calling NewCookie.getName(), the path of the cookie is returned.
The cookies returned in the response header look like this:
Set-Cookie: xsIdEEDB0766347B60DAEAA0AF57226EDD2C=385DF57B79FE0A4D84E04ED43000A81B; path=/; HttpOnly
My code looks something like this. I am just dumping the info to System.out for now because I wanted to look at the values in the debugger.
My question is why ClientResponse.getCookies() does not seem to work. Parsing the headers manually will work, but that just does not seem right. Is there a way to configure the Client or the ClientResponse to correctly get the cookies?
ClientConfig clientConfig = new DefaultClientConfig();
Client client = Client.create(clientConfig);
Builder builder = client.resource(MY_PATH).accept("text/plain");
builder = builder.header(AUTHORIZATION, auth);
ClientResponse response = builder.head();
if (response.getClientResponseStatus() == Status.OK) {
// Look at cookies in the response
List<NewCookie> cs = response.getCookies();
for (NewCookie c : cs) {
System.out.println(c.getName());
System.out.println(c.getValue());
}
// Look at the cookies in the header
List<String> cookies = headers.get("Set-Cookie");
for (String cookie : cookies) {
// example: xsIdEEDB0766347B60DAEAA0AF57226EDD2C=385DF57B79FE0A4D84E04ED43000A81B; path=/; HttpOnly
int x = cookie.indexOf(';');
String cookieNameValue = cookie.substring(0, x);
String[] nameValue = cookieNameValue.split("=");
NewCookie nc = new NewCookie(nameValue[0], nameValue[1]);
}
}

PHP RESTful API accessing Jersey Client POST data

I am using a PHP RESTful API which is consumed by a Java desktop application using jersey 2.21.
Usually, when I send a POST request from AngularJS, I can access the data via:
$data = json_decode(file_get_contents("php://input"));
However, when I use jersey, the data is put in the $_POST array. Here is my Jersey code:
final HashMap<String, String> params = // some hashmap with a few entries
ClientConfig config = new ClientConfig();
Client client = ClientBuilder.newClient(config);
MultivaluedMap formData = new MultivaluedHashMap(params);
WebTarget target = client.target(url);
// Get JSON
String jsonResponse = target.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.entity(formData, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class);
return jsonResponse;
How do I post the data from Jersey so that I can access it via the above PHP call?
I know I can just use the $_POST array, but I need this API to be consumed from a mobile app, Java desktop & an AngularJS app.
Thanks in advance
Thanks to #jonstirling, I got it.
I had to set the content type as JSON. here is the updated code:
ClientConfig config = new ClientConfig();
Client client = ClientBuilder.newClient(config);
WebTarget target = client.target(url);
String data = new Gson().toJson(params);
// POST JSON
Entity json = Entity.entity(data, MediaType.APPLICATION_JSON_TYPE);
Invocation.Builder builder = target.request(MediaType.APPLICATION_JSON_TYPE);
String jsonResponse = builder.post(json, String.class);
return jsonResponse;

Using the Jersey client to do a POST operation

In a Java method, I'd like to use a Jersey client object to do a POST operation on a RESTful web service (also written using Jersey) but am not sure how to use the client to send the values that will be used as FormParam's on the server. I'm able to send query params just fine.
Not done this yet myself, but a quick bit of Google-Fu reveals a tech tip on blogs.oracle.com with examples of exactly what you ask for.
Example taken from the blog post:
MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("name1", "val1");
formData.add("name2", "val2");
ClientResponse response = webResource
.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.post(ClientResponse.class, formData);
That any help?
Starting from Jersey 2.x, the MultivaluedMapImpl class is replaced by MultivaluedHashMap. You can use it to add form data and send it to the server:
WebTarget webTarget = client.target("http://www.example.com/some/resource");
MultivaluedMap<String, String> formData = new MultivaluedHashMap<String, String>();
formData.add("key1", "value1");
formData.add("key2", "value2");
Response response = webTarget.request().post(Entity.form(formData));
Note that the form entity is sent in the format of "application/x-www-form-urlencoded".
It is now the first example in the Jersey Client documentation
Example 5.1. POST request with form parameters
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:9998").path("resource");
Form form = new Form();
form.param("x", "foo");
form.param("y", "bar");
MyJAXBBean bean =
target.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE),
MyJAXBBean.class);
If you need to do a file upload, you'll need to use MediaType.MULTIPART_FORM_DATA_TYPE.
Looks like MultivaluedMap cannot be used with that so here's a solution with FormDataMultiPart.
InputStream stream = getClass().getClassLoader().getResourceAsStream(fileNameToUpload);
FormDataMultiPart part = new FormDataMultiPart();
part.field("String_key", "String_value");
part.field("fileToUpload", stream, MediaType.TEXT_PLAIN_TYPE);
String response = WebResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(String.class, part);
Simplest:
Form form = new Form();
form.add("id", "1");
form.add("name", "supercobra");
ClientResponse response = webResource
.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.post(ClientResponse.class, form);
Also you can try this:
MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("name1", "val1");
formData.add("name2", "val2");
webResource.path("yourJerseysPathPost").queryParams(formData).post();

Categories

Resources