Searching...
Monday, 24 June 2013

Java URL client for Web services

18:37

Restful Java client using Java.Net.URL

Example

package com.vinod.vinod_rest_examples;

import java.io.*;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MyURLClient {

    public static void main(String[] args) {
        try {
            URL url = new URL("http://localhost:8080/xxxxx");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/xml");
            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
            }
            BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
            String response;
            System.out.println("Response from web service :");
            while ((response = br.readLine()) != null) {
                System.out.println(response);
            }
            conn.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }
    }

}
 

0 comments: