Note that there are some explanatory texts on larger screens.

plurals
  1. POJava: how to use UrlConnection to post request with authorization?
    primarykey
    data
    text
    <p>I would like to generate POST request to a server which requires authentication. I tried to use the following method:</p> <pre><code>private synchronized String CreateNewProductPOST (String urlString, String encodedString, String title, String content, Double price, String tags) { String data = "product[title]=" + URLEncoder.encode(title) + "&amp;product[content]=" + URLEncoder.encode(content) + "&amp;product[price]=" + URLEncoder.encode(price.toString()) + "&amp;tags=" + tags; try { URL url = new URL(urlString); URLConnection conn; conn = url.openConnection(); conn.setRequestProperty ("Authorization", "Basic " + encodedString); conn.setDoOutput(true); conn.setDoInput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { // Process line... } wr.close(); rd.close(); return rd.toString(); } catch (MalformedURLException e) { e.printStackTrace(); return e.getMessage(); } catch (IOException e) { e.printStackTrace(); return e.getMessage(); } } </code></pre> <p>but the server doesn't receive the authorization data. The line which is supposed to add authorization data is the following:</p> <pre><code>conn.setRequestProperty ("Authorization", "Basic " + encodedString); </code></pre> <p>and the line </p> <pre><code>BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); </code></pre> <p>also throws an IOException.</p> <p>Anyway I would be very thankful if anyone could suggest any fix of the logic above in order to enable authorization using POST with UrlConnection.</p> <p>but obviously it doesn't work as it is supposed to although if the same logic is used for GET request everything works fine.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload