Вопрос-ответ

Sending HTTP POST Request In Java

Отправка HTTP POST-запроса в Java

Учитывая этот URL:

http://www.example.com/page.php?id=10            

Я хочу отправить id = 10 на сервер page.php, который принимает его методом POST.

Как я могу это сделать с помощью Java?

Я пробовал это :

URL aaa = new URL("http://www.example.com/page.php");
URLConnection ccc = aaa.openConnection();

Но я все еще не могу понять, как отправить его с помощью метода POST.

Переведено автоматически
Ответ 1

Обновленный ответ

Поскольку некоторые классы в исходном ответе устарели в более новой версии Apache HTTP Components, я публикую это обновление.

Кстати, вы можете получить доступ к полной документации для получения дополнительных примеров здесь.

HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://www.a-domain.example/foo/");

// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("param-1", "12345"));
params.add(new BasicNameValuePair("param-2", "Hello!"));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

if (entity != null) {
try (InputStream instream = entity.getContent()) {
// do something useful
}
}

Оригинальный ответ

Я рекомендую использовать Apache HttpClient. это быстрее и проще в реализации.

HttpPost post = new HttpPost("http://jakarata.apache.org/");
NameValuePair[] data = {
new NameValuePair("user", "joe"),
new NameValuePair("password", "bloggs")
};
post.setRequestBody(data);
// execute method and handle any error responses.
...
InputStream in = post.getResponseBodyAsStream();
// handle response.

для получения дополнительной информации проверьте этот URL: http://hc.apache.org /

Ответ 2

Отправить POST-запрос в ванильной Java легко. Начиная с a URL, нам нужно преобразовать его в a URLConnection используя url.openConnection();. После этого нам нужно преобразовать его в HttpURLConnection, чтобы мы могли получить доступ к его setRequestMethod() методу, чтобы установить наш метод. Наконец, мы говорим, что собираемся отправлять данные по соединению.

URL url = new URL("https://www.example.com/login");
URLConnection con = url.openConnection();
HttpURLConnection http = (HttpURLConnection)con;
http.setRequestMethod("POST"); // PUT is another valid option
http.setDoOutput(true);

Затем нам нужно указать, что мы собираемся отправить:

Отправка простой формы

Обычный POST, поступающий из http-формы, имеет четко определенный формат. Нам нужно преобразовать наши входные данные в этот формат:

Map<String,String> arguments = new HashMap<>();
arguments.put("username", "root");
arguments.put("password", "sjh76HSn!"); // This is a fake password obviously
StringJoiner sj = new StringJoiner("&");
for(Map.Entry<String,String> entry : arguments.entrySet())
sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "="
+ URLEncoder.encode(entry.getValue(), "UTF-8"));
byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8);
int length = out.length;

Затем мы можем прикрепить содержимое нашей формы к http-запросу с соответствующими заголовками и отправить его.

http.setFixedLengthStreamingMode(length);
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
http.connect();
try(OutputStream os = http.getOutputStream()) {
os.write(out);
}
// Do something with http.getInputStream()

Отправка JSON

Мы также можем отправить json с помощью Java, это тоже просто:

byte[] out = "{\"username\":\"root\",\"password\":\"password\"}" .getBytes(StandardCharsets.UTF_8);
int length = out.length;

http.setFixedLengthStreamingMode(length);
http.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
http.connect();
try(OutputStream os = http.getOutputStream()) {
os.write(out);
}
// Do something with http.getInputStream()

Помните, что разные серверы принимают разные типы контента для json, смотрите Этот вопрос.


Отправка файлов с помощью java post

Отправка файлов может считаться более сложной в обработке, поскольку формат более сложный. Мы также собираемся добавить поддержку отправки файлов в виде строки, поскольку мы не хотим полностью помещать файл в буфер памяти.

Для этого мы определяем несколько вспомогательных методов:

private void sendFile(OutputStream out, String name, InputStream in, String fileName) {
String o = "Content-Disposition: form-data; name=\"" + URLEncoder.encode(name,"UTF-8")
+ "\"; filename=\"" + URLEncoder.encode(filename,"UTF-8") + "\"\r\n\r\n";
out.write(o.getBytes(StandardCharsets.UTF_8));
byte[] buffer = new byte[2048];
for (int n = 0; n >= 0; n = in.read(buffer))
out.write(buffer, 0, n);
out.write("\r\n".getBytes(StandardCharsets.UTF_8));
}

private void sendField(OutputStream out, String name, String field) {
String o = "Content-Disposition: form-data; name=\""
+ URLEncoder.encode(name,"UTF-8") + "\"\r\n\r\n";
out.write(o.getBytes(StandardCharsets.UTF_8));
out.write(URLEncoder.encode(field,"UTF-8").getBytes(StandardCharsets.UTF_8));
out.write("\r\n".getBytes(StandardCharsets.UTF_8));
}

Затем мы можем использовать эти методы для создания составного post-запроса следующим образом:

String boundary = UUID.randomUUID().toString();
byte[] boundaryBytes =
("--" + boundary + "\r\n").getBytes(StandardCharsets.UTF_8);
byte[] finishBoundaryBytes =
("--" + boundary + "--").getBytes(StandardCharsets.UTF_8);
http.setRequestProperty("Content-Type",
"multipart/form-data; charset=UTF-8; boundary=" + boundary);

// Enable streaming mode with default settings
http.setChunkedStreamingMode(0);

// Send our fields:
try(OutputStream out = http.getOutputStream()) {
// Send our header (thx Algoman)
out.write(boundaryBytes);

// Send our first field
sendField(out, "username", "root");

// Send a seperator
out.write(boundaryBytes);

// Send our second field
sendField(out, "password", "toor");

// Send another seperator
out.write(boundaryBytes);

// Send our file
try(InputStream file = new FileInputStream("test.txt")) {
sendFile(out, "identification", file, "text.txt");
}

// Finish the request
out.write(finishBoundaryBytes);
}


// Do something with http.getInputStream()
Ответ 3
String rawData = "id=10";
String type = "application/x-www-form-urlencoded";
String encodedData = URLEncoder.encode( rawData, "UTF-8" );
URL u = new URL("http://www.example.com/page.php");
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty( "Content-Type", type );
conn.setRequestProperty( "Content-Length", String.valueOf(encodedData.length()));
OutputStream os = conn.getOutputStream();
os.write(encodedData.getBytes());
Ответ 4

Первый ответ был отличным, но мне пришлось добавить try / catch, чтобы избежать ошибок компилятора Java.
Кроме того, у меня возникли проблемы с пониманием того, как читать HttpResponse с библиотеками Java.

Вот более полный код :

/*
* Create the POST request
*/

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", "Bob"));
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
/*
* Execute the HTTP Request
*/

try {
HttpResponse response = httpClient.execute(httpPost);
HttpEntity respEntity = response.getEntity();

if (respEntity != null) {
// EntityUtils to get the response content
String content = EntityUtils.toString(respEntity);
}
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
java