tumblr counter

CXF Restful Client

CXF Restful Client Example explains step by step details of How To Create a CXF REST Client from a deployed Apache CXF Restful service

For Creating Apache CXF Restful Client, We are using java.net.HttpURLConnection.

By using HttpURLConnection, we are invoking the correct exposed methods / operations of restful service.

You can see the below example, which is demonstrating a CXF REST Client Example

Note

You can also find RESTful Java Client Using HttpClient if you need to invoke restful service using Apache HttpClient

Note

For publishing a Restful service, you can follow this tutorial CXF Restful Tutorial. This client is based on mentioned Tutorial

Create CXF Restful Client

Here we showing an example of a CXF REST client, which invoking a POST method of a CXF Restful Service

package com.client;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;

// CXF REST Client Invoking POST Method

public class PostStudentClient {

 
public static void main(String[] args) {
   
try {
     
URL url = new URL("http://localhost:8080/CXFRestfulTutorial/rest/changeName");
      HttpURLConnection conn =
(HttpURLConnection) url.openConnection();
      conn.setDoOutput
(true);
      conn.setRequestMethod
("POST");
      conn.setRequestProperty
("Content-Type", "application/json");

      String input =
"{\"Student\":{\"name\":\"Tom\"}}";

      OutputStream os = conn.getOutputStream
();
      os.write
(input.getBytes());
      os.flush
();

      Scanner scanner;
      String response;
     
if (conn.getResponseCode() != 200) {
       
scanner = new Scanner(conn.getErrorStream());
        response =
"Error From Server \n\n";
     
} else {
       
scanner = new Scanner(conn.getInputStream());
        response =
"Response From Server \n\n";
     
}
     
scanner.useDelimiter("\\Z");
      System.out.println
(response + scanner.next());
      scanner.close
();
      conn.disconnect
();
   
} catch (MalformedURLException e) {
     
e.printStackTrace();
   
} catch (IOException e) {
     
e.printStackTrace();
   
}
  }
}
Output
Response From Server

{"Student":{"name":"HELLO Tom"}}





1 2 Next








2 Responses to “CXF Restful Client”
  1. saurabh 14.10.2013 04:55:37
  1. admin 14.10.2013 11:55:34

Your email address will not be published. Required fields are marked *