A
A
artshelom2016-10-05 23:39:22
Java
artshelom, 2016-10-05 23:39:22

How to pass parameter to httpurlcon??

public static String excutePost(String targetURL, String urlParameters)
{
    URL url;
    HttpURLConnection connection = null;
    try {
        //Create connection
        url = new URL(targetURL);
        connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
//        connection.setRequestProperty("chat_id", "***");
//        connection.setRequestProperty("text", "Hello, world");
        Map<String,Object> params = new LinkedHashMap<>();
        params.put("chat_id", "***");
        params.put("text", "Hello, world");

        connection.setUseCaches (false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        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();
        }
    }
}

I can't figure out how to pass the parameters of a post request to a telegram. Parameters text and chat_id
Help a newbie

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
Zakharov Alexander, 2016-10-06
@AlexZaharow

The parameters passed via POST are just a param1=value1¶m2=value2 format string, but passed in the body of the request, not in the address bar. Here is a good conversion example where escaping is taken into account: stackoverflow.com/questions/7671597/convert-map-to...

connection.setDoOutput(true);  // После этой строки писать всё остальное
StringBuilder sb = new StringBuilder();
  for(HashMap.Entry<String, String> e : queryString.entrySet()){
      if(sb.length() > 0){
          sb.append('&');
      }
      sb.append(URLEncoder.encode(e.getKey(), "UTF-8")).append('=').append(URLEncoder.encode(e.getValue(), "UTF-8"));
  }

// Теперь нужно эти данные передать в тело запроса:

        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.write(sb.toString().getBytes());
        wr.flush();
        wr.close();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question