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 HttpURLConnection connection =
67 (HttpURLConnection) new URL(new String(url_)).openConnection();
68 connection.setRequestMethod(method_);
69 if (contentType_ != null) {
70 connection.setRequestProperty("Content-Type", contentType_);
71 connection.setDoOutput(true);
72 connection.setFixedLengthStreamingMode(body_.size());
73 connection.getOutputStream().write(body_.toByteArray());
75 if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
76 throw new IOException("HTTP request failed: "
77 + connection.getResponseCode() + " " + connection.getResponseMessage());
78 return new HttpResponse(connection);
81 public HttpRequest addParameter(String name, String value)
82 throws UnsupportedEncodingException
84 return addParameter(name, value, "utf-8");
87 public HttpRequest addParameter(String name, String value, String encoding)
88 throws UnsupportedEncodingException
90 return addParameter(name, value.getBytes(encoding), encoding);
93 abstract public HttpRequest addParameter(String name, byte[] value, String encoding);