2007/05/29

Link Crossing borders: REST on Rails



Create: HTTP put
Read: HTTP get
Update: HTTP post
Delete: HTTP delete

Listing 6. Rendering HTML for a JavaScript client

def list
# wants is determined by the http Accept header in the request
@people = Person.find_all
respond_to do |wants|
wants.html
wants.js
wants.xml { render :xml => @people.to_xml }
end
end

Listing 8. Invoking the service from Ruby
require 'net/http'

Net::HTTP.start('localhost', 3000) do |http|
response = http.get('/people/list', 'Accept' => 'text/xml')

#Do something with the response.

puts "Code: #{response.code}"
puts "Message: #{response.message}"
puts "Body:\n #{response.body}"
end

Listing 9. Invoking the service with Java code

package com.rapidred.ws;

import java.net.*;
import java.io.*;

public class SimpleGet {

void get() {

try {
URL url = new URL("http://localhost:3000/people/list");
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("accept", "text/xml");
BufferedReader in =
new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String str;

while ((str = in.readLine()) != null) {
System.out.println(str);
}

in.close();
}
catch (Exception e) {
System.out.println(e);
}
}



Listing 10. Calling HTTP post with Java code
void post() {
try {
String xmlText = " " +
"Maggie" +
"Maggie" +
"maggie@tate.com" +
"
";

URL url = new URL("http://localhost:3000/people/create");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/xml");
OutputStreamWriter wr = new
OutputStreamWriter(conn.getOutputStream());
wr.write(xmlText);
wr.flush();

BufferedReader rd = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
wr.close();
rd.close();
} catch (Exception e) {
System.out.println("Error" + e);
}
}

No comments: