user5122076
user5122076

Reputation:

Posting JSON object in HTTP in Java class

This is the error I am getting when I post a JSON as json.toString() Am stuck with this problem. Need help to overcome this as early as possible

Error code -415
Unsupported Media Type.

Code is

String url = "http://0.0.0.0:0000/XXXX/XXXX?wsdl";
        HttpClient client=new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        post.setHeader("Accept", "application/json");
        post.setHeader("headerValue", "HeaderInformation");

        //setting json object to post request.
        JSONObject jsonObject=jsonValue();
        if(jsonObject!=null ){
            StringEntity entity = new StringEntity(jsonObject.toString(), "UTF8");
            entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            post.setEntity(entity);

            //this is your response:
            HttpResponse response = client.execute(post);
            System.out.println("Response: " + response.getStatusLine());
            System.out.println(response.getStatusLine().toString());
        }else{
            System.out.println("jsonObject is Empty");

Upvotes: 1

Views: 98

Answers (1)

ACV
ACV

Reputation: 10552

This means that your service that is accepting the post does not accept te media type you provide. It is probably annotated with @Consumes (something). You need to find what something is it. You have to specify the media type explicitly when posting.

For example JAX-RS client API:

Client client = ClientBuilder.newClient(new ClientConfig()
            .register(MyClientResponseFilter.class)
            .register(new AnotherClientFilter()));

String entity = client.target("http://example.com/rest")
            .register(FilterForExampleCom.class)
            .path("resource/helloworld")
            .queryParam("greeting", "Hi World!")
            .request(MediaType.TEXT_PLAIN_TYPE)
            .header("some-header", "true")
            .get(String.class);

In your case you need to change:

.request(MediaType.TEXT_PLAIN_TYPE)

Look here: Jersey Client API

Upvotes: 1

Related Questions