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,
41 String name, byte[] value)
44 if (!first) buffer.append("&");
45 buffer.append(URLEncoder.encode(name, "utf-8"));
47 // We really would need a URLEncoder for byte[] (pre-encoded or raw
49 buffer.append(URLEncoder
50 .encode(new String(value, "ascii"), "ascii"));
52 catch (UnsupportedEncodingException e) {
53 throw new AssertionError("Missing encoding");
55 catch (IOException e) {
56 throw new AssertionError("IOException on buffer-based Appendable");
60 public HttpResponse execute() throws MalformedURLException, IOException
62 if (query_.length() > 0) url_.append("?");
64 HttpURLConnection connection = (HttpURLConnection) new URL(new String(
65 url_)).openConnection();
66 connection.setRequestMethod(method_);
67 if (contentType_ != null) {
68 connection.setRequestProperty("Content-Type", contentType_);
69 connection.setDoOutput(true);
70 connection.setFixedLengthStreamingMode(body_.size());
71 connection.getOutputStream().write(body_.toByteArray());
73 if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) throw new IOException(
74 "HTTP request failed: " + connection.getResponseCode() + " "
75 + connection.getResponseMessage());
76 return new HttpResponse(connection);
79 public HttpRequest addParameter(String name, String value)
80 throws UnsupportedEncodingException
82 return addParameter(name, value, "utf-8");
85 public HttpRequest addParameter(String name, String value, String encoding)
86 throws UnsupportedEncodingException
88 return addParameter(name, value.getBytes(encoding), encoding);
91 abstract public HttpRequest addParameter(String name, byte[] value,