Javaで、HTTPリクエストメッセージを作成し、HTTP WebServerに送信する方法を教えてください。
java.net.HttpUrlConnection][1]を使用することができます。
例([ここから][3])を改良したものです。リンク腐敗の場合に含まれます。
public static String executePost(String targetURL, String urlParameters) {
HttpURLConnection connection = null;
try {
//Create connection
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length",
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
[1]: http://download.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html [2]: http://www.exampledepot.com/egs/java.net/pkg.html [3]: http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
Oracle's java tutorial]1より
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");
URLConnection yc = yahoo.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
他の人がApache'sのhttp-clientを勧めるのは知っていますが、それはほとんど必要のない複雑さ(つまり、うまくいかないことが増える)を追加します。単純な作業であれば、java.net.URL
で十分です。
URL url = new URL("http://www.y.com/url");
InputStream is = url.openStream();
try {
/* Now read the retrieved document from the stream. */
...
} finally {
is.close();
}