Отправка запроса HTTP POST в Java
позволяет использовать этот URL...
http://www.example.com/page.php?id=10
(Здесь идентификатор должен быть отправлен в запросе POST)
Я хочу отправить id = 10
на сервер page.php
, который принимает его в методе POST.
Как я могу сделать это из Java?
Я пробовал это:
URL aaa = new URL("http://www.example.com/page.php");
URLConnection ccc = aaa.openConnection();
Но я до сих пор не могу понять, как отправить его через POST
Ответы
Ответ 1
Обновленный ответ:
Так как некоторые из классов в исходном ответе устарели в новой версии HTTP-компонентов Apache, я публикую это обновление.
Кстати, вы можете получить доступ к полной документации для получения дополнительных примеров здесь.
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://www.a-domain.com/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) {
InputStream instream = entity.getContent();
try {
// do something useful
} finally {
instream.close();
}
}
Исходный ответ:
Я рекомендую использовать Apache HttpClient. его быстрее и проще реализовать.
PostMethod post = new PostMethod("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. Начиная с URL
, нам нужно преобразовать его в 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));
}
Затем мы можем использовать эти методы для создания многостраничного почтового запроса следующим образом:
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();
}
Ответ 5
Простым способом использования HTTP-компонентов Apache является
Request.Post("http://www.example.com/page.php")
.bodyForm(Form.form().add("id", "10").build())
.execute()
.returnContent();
Взгляните на Fluent API
Ответ 6
Самый простой способ отправки параметров с запросом на отправку:
String postURL = "http://www.example.com/page.php";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", "10"));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, "UTF-8");
post.setEntity(ent);
HttpClient client = new DefaultHttpClient();
HttpResponse responsePOST = client.execute(post);
Вы сделали. теперь вы можете использовать responsePOST
.
Получите содержимое ответа как строку:
BufferedReader reader = new BufferedReader(new InputStreamReader(responsePOST.getEntity().getContent()), 2048);
if (responsePOST != null) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
System.out.println(" line : " + line);
sb.append(line);
}
String getResponseString = "";
getResponseString = sb.toString();
//use server output getResponseString as string value.
}
Ответ 7
Проводка кода, который может отправлять данные формы в почтовых запросах и работает даже на Java 7
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
String host = mUri.getHost();
urlConnection.setRequestMethod("POST"); // PUT is another valid option
urlConnection.setDoOutput(true);
Map<String,String> arguments = new HashMap<>();
arguments.put("key1", "value");
arguments.put("key2", "value");
StringBuilder sj = new StringBuilder();
for(Map.Entry<String,String> entry : arguments.entrySet()) {
sj.append(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue(), "UTF-8") + "&");
}
byte[] out = sj.toString().getBytes();
urlConnection.setFixedLengthStreamingMode(out.length);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
urlConnection.connect();
try
{
OutputStream os = urlConnection.getOutputStream();
os.write(out);
}
catch (Exception e)
{
}
}
Ответ 8
Я рекомендую использовать http-request, построенный на apache http api.
HttpRequest<String> httpRequest = HttpRequestBuilder.createPost("http://www.example.com/page.php", String.class)
.responseDeserializer(ResponseDeserializer.ignorableDeserializer()).build();
public void send(){
String response = httpRequest.execute("id", "10").get();
}
Ответ 9
Вызов HttpURLConnection.setRequestMethod("POST")
и HttpURLConnection.setDoOutput(true);
Фактически требуется только последний, поскольку POST становится стандартным методом.