Java – envoyer facilement des parameters HTTP via la méthode POST

J’utilise avec succès ce code pour envoyer HTTP requêtes HTTP avec certains parameters via la méthode GET

 void sendRequest(Ssortingng request) { // ie: request = "http://example.com/index.php?param1=a&param2=b&param3=c"; URL url = new URL(request); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", "text/plain"); connection.setRequestProperty("charset", "utf-8"); connection.connect(); } 

Maintenant, il se peut que je doive envoyer les parameters (param1, param2, param3) via la méthode POST car ils sont très longs. Je pensais append un paramètre supplémentaire à cette méthode (c.-à-d. Ssortingng httpMethod).

Comment puis-je changer le code ci-dessus le moins possible pour pouvoir envoyer des parameters via GET ou POST ?

J’espérais que changer

 connection.setRequestMethod("GET"); 

à

 connection.setRequestMethod("POST"); 

aurait fait l’affaire, mais les parameters sont toujours envoyés via la méthode GET.

HttpURLConnection a- HttpURLConnection il une méthode qui pourrait aider? Y at-il une construction Java utile?

Toute aide sera la bienvenue.

Dans une requête GET, les parameters sont envoyés dans le cadre de l’URL.

Dans une requête POST, les parameters sont envoyés en tant que corps de la requête, après les en-têtes.

Pour effectuer un POST avec HttpURLConnection, vous devez écrire les parameters sur la connexion après avoir ouvert la connexion.

Ce code devrait vous aider à démarrer:

 Ssortingng urlParameters = "param1=a&param2=b&param3=c"; byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 ); int postDataLength = postData.length; Ssortingng request = "http://example.com/index.php"; URL url = new URL( request ); HttpURLConnection conn= (HttpURLConnection) url.openConnection(); conn.setDoOutput( true ); conn.setInstanceFollowRedirects( false ); conn.setRequestMethod( "POST" ); conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty( "charset", "utf-8"); conn.setRequestProperty( "Content-Length", Integer.toSsortingng( postDataLength )); conn.setUseCaches( false ); try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) { wr.write( postData ); } 

Voici un exemple simple qui soumet un formulaire, puis vide la page de résultats dans System.out . Modifiez l’URL et les parameters POST, le cas échéant:

 import java.io.*; import java.net.*; import java.util.*; class Test { public static void main(Ssortingng[] args) throws Exception { URL url = new URL("http://example.net/new-message.php"); Map params = new LinkedHashMap<>(); params.put("name", "Freddie the Fish"); params.put("email", "fishie@seamail.example.com"); params.put("reply_to_thread", 10394); params.put("message", "Shark attacks in Botany Bay have gotten out of control. We need more defensive dolphins to protect the schools here, but Mayor Porpoise is too busy stuffing his snout with lobsters. He's so shellfish."); StringBuilder postData = new StringBuilder(); for (Map.Entry param : params.entrySet()) { if (postData.length() != 0) postData.append('&'); postData.append(URLEncoder.encode(param.getKey(), "UTF-8")); postData.append('='); postData.append(URLEncoder.encode(Ssortingng.valueOf(param.getValue()), "UTF-8")); } byte[] postDataBytes = postData.toSsortingng().getBytes("UTF-8"); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", Ssortingng.valueOf(postDataBytes.length)); conn.setDoOutput(true); conn.getOutputStream().write(postDataBytes); Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); for (int c; (c = in.read()) >= 0;) System.out.print((char)c); } } 

Si vous voulez le résultat sous forme de Ssortingng au lieu de l’imprimer directement:

  SsortingngBuilder sb = new SsortingngBuilder(); for (int c; (c = in.read()) >= 0;) sb.append((char)c); Ssortingng response = sb.toSsortingng(); 

Je n’ai pas pu obtenir l’exemple d’ Alan pour faire le post, alors j’ai fini avec ceci:

 Ssortingng urlParameters = "param1=a&param2=b&param3=c"; URL url = new URL("http://example.com/index.php"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(urlParameters); writer.flush(); Ssortingng line; BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = reader.readLine()) != null) { System.out.println(line); } writer.close(); reader.close(); 

Je trouve que HttpURLConnection très lourd à utiliser. Et vous devez écrire beaucoup de code passe-partout, enclin aux erreurs. J’avais besoin d’un wrapper léger pour mes projets Android et je suis sorti avec une bibliothèque que vous pouvez également utiliser: DavidWebb .

L’exemple ci-dessus pourrait être écrit comme ceci:

 Webb webb = Webb.create(); webb.post("http://example.com/index.php") .param("param1", "a") .param("param2", "b") .param("param3", "c") .ensureSuccess() .asVoid(); 

Vous pouvez trouver une liste de bibliothèques alternatives sur le lien fourni.

Je vois que d’autres réponses ont donné l’alternative, personnellement je pense que intuitivement vous faites la bonne chose;). Désolé, chez devoxx où plusieurs orateurs ont parlé de ce genre de choses.

C’est pourquoi j’utilise personnellement les bibliothèques HTTPClient / HttpCore d’Apache pour effectuer ce type de travail. Je trouve que leur API est plus facile à utiliser que le support HTTP natif de Java. YMMV bien sûr!

 import java.net.*; public class Demo{ public static void main(){ Ssortingng data = "data=Hello+World!"; URL url = new URL("http://localhost:8084/WebListenerServer/webListener"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); con.getOutputStream().write(data.getBytes("UTF-8")); con.getInputStream(); } } 

J’ai lu les réponses ci-dessus et j’ai créé une classe d’utilitaires pour simplifier la requête HTTP. J’espère que cela vous aidera.

Appel de méthode

  // send params with Hash Map HashMap params = new HashMap(); params.put("email","me@example.com"); params.put("password","12345"); //server url Ssortingng url = "http://www.example.com"; // static class "HttpUtility" with static method "newRequest(url,method,callback)" HttpUtility.newRequest(url,HttpUtility.METHOD_POST,params, new HttpUtility.Callback() { @Override public void OnSuccess(Ssortingng response) { // on success System.out.println("Server OnSuccess response="+response); } @Override public void OnError(int status_code, Ssortingng message) { // on error System.out.println("Server OnError status_code="+status_code+" message="+message); } }); 

Classe utilitaire

 import java.io.*; import java.net.*; import java.util.HashMap; import java.util.Map; import static java.net.HttpURLConnection.HTTP_OK; public class HttpUtility { public static final int METHOD_GET = 0; // METHOD GET public static final int METHOD_POST = 1; // METHOD POST // Callback interface public interface Callback { // abstract methods public void OnSuccess(Ssortingng response); public void OnError(int status_code, Ssortingng message); } // static method public static void newRequest(Ssortingng web_url, int method, HashMap < String, String > params, Callback callback) { // thread for handling async task new Thread(new Runnable() { @Override public void run() { try { Ssortingng url = web_url; // write GET params,append with url if (method == METHOD_GET && params != null) { for (Map.Entry < String, String > item: params.entrySet()) { Ssortingng key = URLEncoder.encode(item.getKey(), "UTF-8"); Ssortingng value = URLEncoder.encode(item.getValue(), "UTF-8"); if (!url.contains("?")) { url += "?" + key + "=" + value; } else { url += "&" + key + "=" + value; } } } HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection(); urlConnection.setDoOutput(true); // write POST params urlConnection.setUseCaches(false); urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // handle url encoded form data urlConnection.setRequestProperty("charset", "utf-8"); if (method == METHOD_GET) { urlConnection.setRequestMethod("GET"); } else if (method == METHOD_POST) { urlConnection.setRequestMethod("POST"); } //write POST data if (method == METHOD_POST && params != null) { SsortingngBuilder postData = new SsortingngBuilder(); for (Map.Entry < String, String > item: params.entrySet()) { if (postData.length() != 0) postData.append('&'); postData.append(URLEncoder.encode(item.getKey(), "UTF-8")); postData.append('='); postData.append(URLEncoder.encode(Ssortingng.valueOf(item.getValue()), "UTF-8")); } byte[] postDataBytes = postData.toSsortingng().getBytes("UTF-8"); urlConnection.setRequestProperty("Content-Length", Ssortingng.valueOf(postDataBytes.length)); urlConnection.getOutputStream().write(postDataBytes); } // server response code int responseCode = urlConnection.getResponseCode(); if (responseCode == HTTP_OK && callback != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); SsortingngBuilder response = new SsortingngBuilder(); Ssortingng line; while ((line = reader.readLine()) != null) { response.append(line); } // callback success callback.OnSuccess(response.toSsortingng()); reader.close(); // close BufferReader } else if (callback != null) { // callback error callback.OnError(responseCode, urlConnection.getResponseMessage()); } urlConnection.disconnect(); // disconnect connection } catch (IOException e) { e.printStackTrace(); if (callback != null) { // callback error callback.OnError(500, e.getLocalizedMessage()); } } } }).start(); // start thread } } 

J’ai eu le même problème. Je voulais envoyer des données via POST. J’ai utilisé le code suivant:

  URL url = new URL("http://example.com/getval.php"); Map params = new LinkedHashMap<>(); params.put("param1", param1); params.put("param2", param2); StringBuilder postData = new StringBuilder(); for (Map.Entry param : params.entrySet()) { if (postData.length() != 0) postData.append('&'); postData.append(URLEncoder.encode(param.getKey(), "UTF-8")); postData.append('='); postData.append(URLEncoder.encode(Ssortingng.valueOf(param.getValue()), "UTF-8")); } Ssortingng urlParameters = postData.toSsortingng(); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(urlParameters); writer.flush(); Ssortingng result = ""; Ssortingng line; BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = reader.readLine()) != null) { result += line; } writer.close(); reader.close() System.out.println(result); 

J’ai utilisé Jsoup pour l’parsing:

  Document doc = Jsoup.parseBodyFragment(value); Iterator opts = doc.select("option").iterator(); for (;opts.hasNext();) { Element item = opts.next(); if (item.hasAttr("value")) { System.out.println(item.attr("value")); } } 

Essayez ce modèle:

 public static PricesResponse getResponse(EventRequestRaw request) { // Ssortingng urlParameters = "param1=a&param2=b&param3=c"; Ssortingng urlParameters = Piping.serialize(request); HttpURLConnection conn = RestClient.getPOSTConnection(endPoint, urlParameters); PricesResponse response = null; try { // POST OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(urlParameters); writer.flush(); // RESPONSE BufferedReader reader = new BufferedReader(new InputStreamReader((conn.getInputStream()), StandardCharsets.UTF_8)); Ssortingng json = Buffering.getSsortingng(reader); response = (PricesResponse) Piping.deserialize(json, PricesResponse.class); writer.close(); reader.close(); } catch (Exception e) { e.printStackTrace(); } conn.disconnect(); System.out.println("PricesClient: " + response.toSsortingng()); return response; } public static HttpURLConnection getPOSTConnection(Ssortingng endPoint, Ssortingng urlParameters) { return RestClient.getConnection(endPoint, "POST", urlParameters); } public static HttpURLConnection getConnection(Ssortingng endPoint, Ssortingng method, Ssortingng urlParameters) { System.out.println("ENDPOINT " + endPoint + " METHOD " + method); HttpURLConnection conn = null; try { URL url = new URL(endPoint); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(method); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "text/plain"); } catch (IOException e) { e.printStackTrace(); } return conn; } 

ici j’ai envoyé jsonobject comme paramètre // jsonobject = {“name”: “lucifer”, “pass”: “abc”} // serverUrl = ” http://192.168.100.12/testing ” //host=192.168.100.12

  public static Ssortingng getJson(Ssortingng serverUrl,Ssortingng host,Ssortingng jsonobject){ SsortingngBuilder sb = new SsortingngBuilder(); Ssortingng http = serverUrl; HttpURLConnection urlConnection = null; try { URL url = new URL(http); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setDoOutput(true); urlConnection.setRequestMethod("POST"); urlConnection.setUseCaches(false); urlConnection.setConnectTimeout(50000); urlConnection.setReadTimeout(50000); urlConnection.setRequestProperty("Content-Type", "application/json"); urlConnection.setRequestProperty("Host", host); urlConnection.connect(); //You Can also Create JSONObject here OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream()); out.write(jsonobject);// here i sent the parameter out.close(); int HttpResult = urlConnection.getResponseCode(); if (HttpResult == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader( urlConnection.getInputStream(), "utf-8")); Ssortingng line = null; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); Log.e("new Test", "" + sb.toSsortingng()); return sb.toSsortingng(); } else { Log.e(" ", "" + urlConnection.getResponseMessage()); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (urlConnection != null) urlConnection.disconnect(); } return null; } 

Je recommande vivement http-request basé sur Apache http api.

Pour votre cas, vous pouvez voir l’exemple:

 private static final HttpRequest HTTP_REQUEST = HttpRequestBuilder.createPost("http://example.com/index.php", Ssortingng.class) .responseDeserializer(ResponseDeserializer.ignorableDeserializer()) .build(); public void sendRequest(Ssortingng request){ Ssortingng parameters = request.split("\\?")[1]; ResponseHandler responseHandler = HTTP_REQUEST.executeWithQuery(parameters); System.out.println(responseHandler.getStatusCode()); System.out.println(responseHandler.get()); //prints response body } 

Si le corps de la réponse ne vous intéresse pas

 private static final HttpRequest HTTP_REQUEST = HttpRequestBuilder.createPost("http://example.com/index.php").build(); public void sendRequest(Ssortingng request){ ResponseHandler responseHandler = HTTP_REQUEST.executeWithQuery(parameters); } 

Pour l’envoi d’une demande générale avec http-request : lisez la documentation et consultez mes réponses Demande HTTP POST avec une chaîne JSON dans JAVA , envoi d’une demande HTTP POST en Java , HTTP POST avec JSON en Java

Bonjour, utilisez cette classe pour améliorer votre méthode de publication

 public static JSONObject doPostRequest(HashMap data, Ssortingng url) { try { RequestBody requestBody; MultipartBuilder mBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); if (data != null) { for (Ssortingng key : data.keySet()) { Ssortingng value = data.get(key); Utility.printLog("Key Values", key + "-----------------" + value); mBuilder.addFormDataPart(key, value); } } else { mBuilder.addFormDataPart("temp", "temp"); } requestBody = mBuilder.build(); Request request = new Request.Builder() .url(url) .post(requestBody) .build(); OkHttpClient client = new OkHttpClient(); Response response = client.newCall(request).execute(); Ssortingng responseBody = response.body().ssortingng(); Utility.printLog("URL", url); Utility.printLog("Response", responseBody); return new JSONObject(responseBody); } catch (UnknownHostException | UnsupportedEncodingException e) { JSONObject jsonObject=new JSONObject(); try { jsonObject.put("status","false"); jsonObject.put("message",e.getLocalizedMessage()); } catch (JSONException e1) { e1.printStackTrace(); } Log.e(TAG, "Error: " + e.getLocalizedMessage()); } catch (Exception e) { e.printStackTrace(); JSONObject jsonObject=new JSONObject(); try { jsonObject.put("status","false"); jsonObject.put("message",e.getLocalizedMessage()); } catch (JSONException e1) { e1.printStackTrace(); } Log.e(TAG, "Other Error: " + e.getLocalizedMessage()); } return null; } 

J’ai pris la réponse de Boann et l’ai utilisée pour créer un générateur de chaînes de requête plus flexible qui supporte les listes et les tableaux, tout comme la méthode http_build_query de php:

 public static byte[] httpBuildQuerySsortingng(Map postsData) throws UnsupportedEncodingException { SsortingngBuilder postData = new SsortingngBuilder(); for (Map.Entry param : postsData.entrySet()) { if (postData.length() != 0) postData.append('&'); Object value = param.getValue(); Ssortingng key = param.getKey(); if(value instanceof Object[] || value instanceof List) { int size = value instanceof Object[] ? ((Object[])value).length : ((List)value).size(); for(int i = 0; i < size; i++) { Object val = value instanceof Object[] ? ((Object[])value)[i] : ((List)value).get(i); if(i>0) postData.append('&'); postData.append(URLEncoder.encode(key + "[" + i + "]", "UTF-8")); postData.append('='); postData.append(URLEncoder.encode(Ssortingng.valueOf(val), "UTF-8")); } } else { postData.append(URLEncoder.encode(key, "UTF-8")); postData.append('='); postData.append(URLEncoder.encode(Ssortingng.valueOf(value), "UTF-8")); } } return postData.toSsortingng().getBytes("UTF-8"); } 

La méthode GET et POST est définie comme ceci … Deux types d’appel api 1) get () et 2) post (). Méthode get () pour obtenir la valeur du tableau api json pour obtenir la valeur & post () méthode utilisée dans notre publication de données dans l’URL et obtenir une réponse.

  public class HttpClientForExample { private final Ssortingng USER_AGENT = "Mozilla/5.0"; public static void main(Ssortingng[] args) throws Exception { HttpClientExample http = new HttpClientExample(); System.out.println("Testing 1 - Send Http GET request"); http.sendGet(); System.out.println("\nTesting 2 - Send Http POST request"); http.sendPost(); } // HTTP GET request private void sendGet() throws Exception { Ssortingng url = "http://www.google.com/search?q=developer"; HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url); // add request header request.addHeader("User-Agent", USER_AGENT); HttpResponse response = client.execute(request); System.out.println("\nSending 'GET' request to URL : " + url); System.out.println("Response Code : " + response.getStatusLine().getStatusCode()); BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); SsortingngBuffer result = new SsortingngBuffer(); Ssortingng line = ""; while ((line = rd.readLine()) != null) { result.append(line); } System.out.println(result.toSsortingng()); } // HTTP POST request private void sendPost() throws Exception { Ssortingng url = "https://selfsolve.apple.com/wcResults.do"; HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url); // add header post.setHeader("User-Agent", USER_AGENT); List urlParameters = new ArrayList(); urlParameters.add(new BasicNameValuePair("sn", "C02G8416DRJM")); urlParameters.add(new BasicNameValuePair("cn", "")); urlParameters.add(new BasicNameValuePair("locale", "")); urlParameters.add(new BasicNameValuePair("caller", "")); urlParameters.add(new BasicNameValuePair("num", "12345")); post.setEntity(new UrlEncodedFormEntity(urlParameters)); HttpResponse response = client.execute(post); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + post.getEntity()); System.out.println("Response Code : " + response.getStatusLine().getStatusCode()); BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); SsortingngBuffer result = new SsortingngBuffer(); Ssortingng line = ""; while ((line = rd.readLine()) != null) { result.append(line); } System.out.println(result.toSsortingng()); } } 

Apparemment, vous devez également appeler connection.getOutputStream() “au moins une fois” (ainsi que setDoOutput(true) ) pour le traiter comme un POST.

Le code minimum requirejs est donc:

  URL url = new URL(urlSsortingng); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //connection.setRequestMethod("POST"); this doesn't seem to do anything at all..so not useful connection.setDoOutput(true); // set it to POST...not enough by itself however, also need the getOutputStream call... connection.connect(); connection.getOutputStream().close(); 

Vous pouvez même utiliser les parameters de style “GET” dans urlSsortingng, de manière surprenante. Bien que cela puisse confondre les choses.

Vous pouvez également utiliser NameValuePair apparemment.