Basit bir RESTful Webservice Client Servlet i

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;

/**
 *
 * @author ugur
 */

public class SimpleClient extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        GetMethod getMethod = null;
        try {
            getMethod = new GetMethod("http://ws.audioscrobbler.com/2.0/?method=artist.search&artist=metallica&api_key=APIKEY");
            HttpClient httpClient = new HttpClient();
            int statusCode = httpClient.executeMethod(getMethod);
            if (statusCode == HttpStatus.SC_OK) {
                out.print(new String(getMethod.getResponseBody()));
            } else {
                out.print("HTTP error with code: " + statusCode);
            }
        } catch (Exception e) {
            // Send any errors to the view
            out.print(e.getMessage());
        } finally {
            if (getMethod != null) {
                getMethod.releaseConnection();
            }
        }
    }
}

Kullanılan kütüphaneler:

Common Apache Logging
Common Apache Codec
Common Apache httpclient

Leave a Reply