1 package de.j32.httplib;
3 import java.io.ByteArrayOutputStream;
4 import java.io.IOException;
5 import java.io.UnsupportedEncodingException;
6 import java.net.HttpURLConnection;
7 import java.net.MalformedURLException;
9 import java.net.URLEncoder;
11 public abstract class HttpRequest
14 StringBuffer query_ = new StringBuffer();
16 ByteArrayOutputStream body_ = new ByteArrayOutputStream();
19 public HttpRequest(String url, String method)
21 url_ = new StringBuffer(url);
25 protected StringBuffer query()
30 protected ByteArrayOutputStream body()
35 protected void setContentType(String c)
40 protected static void appendParameter(Appendable buffer, boolean first, String name, byte[] value)
45 buffer.append(URLEncoder.encode(name,"utf-8"));
47 // We really would need a URLEncoder for byte[] (pre-encoded or raw date)
48 buffer.append(URLEncoder.encode(new String(value,"ascii"),"ascii"));
50 catch (UnsupportedEncodingException e)
52 throw new AssertionError("Missing encoding");
56 throw new AssertionError("IOException on buffer-based Appendable");
60 public HttpResponse execute()
61 throws MalformedURLException, IOException
63 if (query_.length() > 0)
66 System.out.println("Opening: " + url_);
67 HttpURLConnection connection =
68 (HttpURLConnection) new URL(new String(url_)).openConnection();
69 System.out.println("Request method: " + method_);
70 connection.setRequestMethod(method_);
71 if (contentType_ != null) {
72 System.out.println("Content-Type: " + contentType_);
73 connection.setRequestProperty("Content-Type", contentType_);
74 connection.setDoOutput(true);
75 System.out.println("Body size: " + body_.size());
76 connection.setFixedLengthStreamingMode(body_.size());
77 System.out.println("Body:");
78 System.out.println(body_.toString());
79 connection.getOutputStream().write(body_.toByteArray());
80 System.out.println("done...");
82 if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
83 throw new IOException("HTTP request failed: "
84 + connection.getResponseCode() + " " + connection.getResponseMessage());
85 System.out.println("response ok");
86 return new HttpResponse(connection);
89 public HttpRequest addParameter(String name, String value)
90 throws UnsupportedEncodingException
92 return addParameter(name, value, "utf-8");
95 public HttpRequest addParameter(String name, String value, String encoding)
96 throws UnsupportedEncodingException
98 return addParameter(name, value.getBytes(encoding), encoding);
101 abstract public HttpRequest addParameter(String name, byte[] value, String encoding);