supposons cette URL …
http://www.example.com/page.php?id=10
(Ici, l’identifiant doit être envoyé dans une requête POST)
Je veux envoyer l’ id = 10
à la page.php
du serveur, qui l’accepte dans une méthode POST.
Comment puis-je le faire depuis Java?
J’ai essayé ceci:
URL aaa = new URL("http://www.example.com/page.php"); URLConnection ccc = aaa.openConnection();
Mais je n’arrive toujours pas à comprendre comment l’envoyer via POST
Étant donné que certaines des classes, dans la réponse d’origine, sont obsolètes dans la version plus récente des composants HTTP Apache, je publie cette mise à jour.
En passant, vous pouvez accéder à la documentation complète pour plus d’exemples ici .
HttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost("http://www.a-domain.com/foo/"); // Request parameters and other properties. List params = new ArrayList (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(); } }
Je recommande d’utiliser Apache HttpClient. c’est plus rapide et plus facile à mettre en œuvre.
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.
pour plus d’informations, consultez cette URL: http://hc.apache.org/
L’envoi d’une requête POST est facile dans Java. En commençant par une URL
, nous devons la convertir en URLConnection
utilisant url.openConnection();
. Après cela, nous devons le HttpURLConnection
, afin que nous puissions accéder à sa méthode setRequestMethod()
pour définir notre méthode. Nous disons enfin que nous allons envoyer des données via la connexion.
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);
Nous devons ensuite indiquer ce que nous allons envoyer:
Un POST normal provenant d’une forme http a un format bien défini . Nous devons convertir notre entrée dans ce format:
Map arguments = new HashMap<>(); arguments.put("username", "root"); arguments.put("password", "sjh76HSn!"); // This is a fake password obviously StringJoiner sj = new StringJoiner("&"); for(Map.Entry entry : arguments.entrySet()) sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue(), "UTF-8")); byte[] out = sj.toSsortingng().getBytes(StandardCharsets.UTF_8); int length = out.length;
Nous pouvons alors joindre notre contenu de formulaire à la requête http avec des en-têtes appropriés et l’envoyer.
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()
Nous pouvons également envoyer json en utilisant java, c’est aussi facile:
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()
N’oubliez pas que différents serveurs acceptent différents types de contenu pour json, voir cette question.
L’envoi de fichiers peut être considéré comme plus difficile à gérer car le format est plus complexe. Nous allons également append un support pour l’envoi des fichiers sous forme de chaîne, car nous ne voulons pas mettre le fichier en mémoire tampon dans son intégralité.
Pour cela, nous définissons des méthodes d’assistance:
private void sendFile(OutputStream out, Ssortingng name, InputStream in, Ssortingng fileName) { Ssortingng 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, Ssortingng name, Ssortingng field) { Ssortingng 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)); }
Nous pouvons ensuite utiliser ces méthodes pour créer une demande de publication en plusieurs parties comme suit:
Ssortingng boundary = UUID.randomUUID().toSsortingng(); 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()
Ssortingng rawData = "id=10"; Ssortingng type = "application/x-www-form-urlencoded"; Ssortingng 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", Ssortingng.valueOf(encodedData.length())); OutputStream os = conn.getOutputStream(); os.write(encodedData.getBytes());
La première réponse a été géniale, mais j’ai dû append try / catch pour éviter les erreurs de compilation Java.
En outre, j’ai eu du HttpResponse
à comprendre comment lire HttpResponse
avec les bibliothèques Java.
Voici le code plus complet:
/* * Create the POST request */ HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://example.com/"); // Request parameters and other properties. List params = new ArrayList (); 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 Ssortingng content = EntityUtils.toSsortingng(respEntity); } } catch (ClientProtocolException e) { // writing exception to log e.printStackTrace(); } catch (IOException e) { // writing exception to log e.printStackTrace(); }
Un moyen simple d’utiliser Apache HTTP Components est
Request.Post("http://www.example.com/page.php") .bodyForm(Form.form().add("id", "10").build()) .execute() .returnContent();
Jetez un coup d’œil à l’ API Fluent
moyen le plus simple d’envoyer des parameters avec la requête post:
Ssortingng postURL = "http://www.example.com/page.php"; HttpPost post = new HttpPost(postURL); List params = new ArrayList (); 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);
Vous avez fait. maintenant vous pouvez utiliser responsePOST
. Obtenir le contenu de la réponse sous forme de chaîne:
BufferedReader reader = new BufferedReader(new InputStreamReader(responsePOST.getEntity().getContent()), 2048); if (responsePOST != null) { SsortingngBuilder sb = new SsortingngBuilder(); Ssortingng line; while ((line = reader.readLine()) != null) { System.out.println(" line : " + line); sb.append(line); } Ssortingng getResponseSsortingng = ""; getResponseSsortingng = sb.toSsortingng(); //use server output getResponseSsortingng as ssortingng value. }
Je recommande d’utiliser http-request basé sur Apache http api.
HttpRequest httpRequest = HttpRequestBuilder.createPost("http://www.example.com/page.php", Ssortingng.class) .responseDeserializer(ResponseDeserializer.ignorableDeserializer()).build(); public void send(){ Ssortingng response = httpRequest.execute("id", "10").get(); }
Appelez HttpURLConnection.setRequestMethod("POST")
et HttpURLConnection.setDoOutput(true);
En fait, seul ce dernier est nécessaire car POST devient alors la méthode par défaut.