csoler
csoler

Reputation: 818

Sending Multipart request with Jersey Client

I am trying to write a client in Java to obtain data from a RESTful web service. I have gone through several tutorials and videos but there is something I'm not understanding. Let me start off with this. I was able to write a clientin PHP using PEST to obtain a successful response. This is an example of how the request is made:

<?php
    require_once('vendor\educoder\pest\Pest.php');

    $sourceCredentials = array(
        "SourceName" => 'username',
        "Password" => 'password',
        "SiteID" => siteID);


    $params = array(
        "ResponseFormat" => 'JSON',
        "ResponseDetial => 'Full'");

    $request = array_merge(array("SourceCredentials"=>$sourceCredentials),$params);

    $pest = new Pest('https://api.something.com');

    $results = json_decode($pest->post('ClientService/GetClients',$request));

    $clients = $results->Clients;

I found somethings that were awkward, I'm not very familiar with RESTful clients. For some reason the site uses POST request instead of GET request. The credentials are passed in the Body as form-data as well as any query parameters. The tutorials i've viewed are not set up like this. I am not sure how to write this request in Java using Jersey. Can anyone give me some pointers on setting up this request using Jersey-client?

enter image description here

Upvotes: 0

Views: 2119

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 208944

form-data in Postman is for multipart/form-data. For that you'll want to use the multipart module with the Jersey client. As far as code, you would just do something like

Client client = ClientBuilder.newBuilder()
         .register(MultiPartFeature.class)
         .build();
FormDataMultiPart multiPart = new FormDataMultiPart()
        .field("SourceCredentials[SourceName]", "...")
        .field("ResponseFormat", "JSON")
        .field("...", "...");
Response response = client.target(url)
        .request()
        .header("...", "...")
        .post(Entity.entity(multiPart, multiPart.getMediaType());

And make sure you have the multipart dependencies.

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-multipart</artifactId>
    <version${jersey2.version}</version>
</dependency>

Upvotes: 2

Related Questions