Showing posts with label XML. Show all posts
Showing posts with label XML. Show all posts

Web Service REST Calls


REST Web Services APIs

There are several ways to make Yahoo! Web Services REST requests using Java.
HTTP GET Requests
An HTTP GET request is all you need to retrieve basic search results from the Yahoo! Search Web Service. GET requests are easy to debug because you can paste it in your web browser and quickly see if the query has been constructed properly. Some web services require requests via POST for tasks such as image uploading or the modification of HTTP headers to set cookies. We will cover both GET and POST requests in the following examples.
The first example is a request for the keyword “umbrella” that returns 10 results:
String request = "http://api.search.yahoo.com/WebSearchService/V1/webSearch?
appid=YahooDemo&query=umbrella&results=10";
We make a simple HTTP GET request to retrieve the results:
HttpClient client = new HttpClient();
GetMethod method = new GetMethod(request);
// Send GET request
int statusCode = client.executeMethod(method);
Next, we process the response from Yahoo! Web Services and print the XML response to the console:
InputStream rstream = null;
rstream = method.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
String line;
while ((line = br.readLine()) != null) 
System.out.println(line);
}
br.close();
A complete code example is shown below in the  YahooWebServiceGet.java
import java.io.*;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;

public class YahooWebServiceGet {

public static void main(String[] args) throws Exception {
String request = "http://api.search.yahoo.com/WebSearchService/V1/webSearch?appid=YahooDemo&
query=umbrella&results=10";

HttpClient client = new HttpClient();
GetMethod method = new GetMethod(request);

// Send GET request
int statusCode = client.executeMethod(method);

if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
InputStream rstream = null;

// Get the response body
rstream = method.getResponseBodyAsStream();

// Process the response from Yahoo! Web Services
BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}

}
HTTP POST Requests
POST requests are used by web browsers when submitting data from HTML forms. The content type “multipart/form-data” should be used for submitting forms that contain files, non-ASCII data, and binary data.
For POST requests, we construct the POST data separately from the request URL and parameters.
String request = "http://api.search.yahoo.com/WebSearchService/V1/webSearch";
HttpClient client = new HttpClient();

PostMethod method = new PostMethod(request);

// Add POST parameters

method.addParameter("appid","YahooDemo");

method.addParameter("query","umbrella");

method.addParameter("results","10");

// Send POST request

int statusCode = client.executeMethod(method);

InputStream rstream = null;

// Get the response body

rstream = method.getResponseBodyAsStream();
The response is the same as the first example and can be processed in the same way.
A complete code example is shown in  YahooWebServicePost.java
import java.io.*;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;

public class YahooWebServicePost {

public static void main(String[] args) throws Exception {
String request = "http://api.search.yahoo.com/WebSearchService/V1/webSearch";

HttpClient client = new HttpClient();
PostMethod method = new PostMethod(request);

method.addParameter("appid","YahooDemo");
method.addParameter("query","umbrella");
method.addParameter("results","10");

// Send POST request
int statusCode = client.executeMethod(method);

if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
InputStream rstream = null;

// Get the response body
rstream = method.getResponseBodyAsStream();

// Process the response from Yahoo! Web Services
BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
}
POST Requests with Sockets
Here’s a POST example where we use sockets instead of the URL and URLConnection objects.
// Create POST data string

String postdata = "appid" + "=" + URLEncoder.encode("YahooDemo", "UTF-8");

postdata += "&" + "query" + "=" + URLEncoder.encode("umbrella", "UTF-8");

postdata += "&" + "results" + "=" + URLEncoder.encode("10", "UTF-8");
// Create a socket to the host

String hostname = "api.search.yahoo.com";

int port = 80;

InetAddress addr = InetAddress.getByName(hostname);

Socket socket = new Socket(addr, port);
// Send header

String path = "/WebSearchService/V1/webSearch";

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));

bw.write("POST " + path + " HTTP/1.0\r\n");

bw.write("Content-Length: " + postdata.length() + "\r\n");

bw.write("Content-Type: application/x-www-form-urlencoded\r\n");

bw.write("\r\n");
// Send POST data string

bw.write(postdata);

bw.flush();
A complete code example is shown in  YahooWebServicePostSocket.java
import java.net.*;
import java.io.*;

public class YahooWebServicePostSocket {

public static void main(String[] args) {
try {

// Create POST data string
String postdata = "appid" + "=" + URLEncoder.encode("YahooDemo", "UTF-8");
postdata += "&" + "query" + "=" + URLEncoder.encode("umbrella", "UTF-8");
postdata += "&" + "results" + "=" + URLEncoder.encode("10", "UTF-8");

// Create a socket to the host
String hostname = "api.search.yahoo.com";
int port = 80;
InetAddress addr = InetAddress.getByName(hostname);
Socket socket = new Socket(addr, port);

// Send header
String path = "/WebSearchService/V1/webSearch";
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
bw.write("POST " + path + " HTTP/1.0\r\n");
bw.write("Content-Length: " + postdata.length() + "\r\n");
bw.write("Content-Type: application/x-www-form-urlencoded\r\n");
bw.write("\r\n");

// Send POST data string
bw.write(postdata);
bw.flush();

// Process the response from Yahoo! Web Services
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
bw.close();
br.close();
} catch (Exception e) {
System.out.println("Web services request failed");
System.err.println(e.getMessage());
e.printStackTrace(System.err);
}

}

}

CSV vs XML vs JSON

CSV vs XML vs JSON – Which is the Best Response Data Format?

Whether you are building a thin client (web application) or thick client (client-server application) at some point you are probably making requests to a web server and need a good data format for responses. As of today, there are three major data formats being used to transmit data from a web server to a client: CSV, XML, and JSON. In order to develop an application with a solid architecture, it’s a good idea to understand the differences between each format and know when to use them. The purpose of this post is to define each data format, lay out the pros and cons for each, and discover which situations work best with each format.

Java API for XML Processing (JAXP)


Java API for XML Processing (JAXP)

The Java API for XML Processing (JAXP) allows applications to parse and transform XML documents 
using an API that is independent of any particular XML processor implementation, without changing the XML processor implementations & without impacting their applications. JAXP 1.1 supports the following standards:

SAX version 2.0
DOM Level 2
XSLT 1.0

The API relies on the factory design pattern to create new SAX parser, DOM document builder or style sheet engines. Below are typical examples of using the API to process an XML document using respectively, SAX, DOM and XSLT.