小编典典

Java:如何使用UrlConnection发布具有授权的请求?

java

我想向需要身份验证的服务器生成POST请求。我尝试使用以下方法:

private synchronized String CreateNewProductPOST (String urlString, String encodedString, String title, String content, Double price, String tags) {

    String data = "product[title]=" + URLEncoder.encode(title) +
                "&product[content]=" + URLEncoder.encode(content) + 
                "&product[price]=" + URLEncoder.encode(price.toString()) +
                "&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();
    } 
}

但服务器未收到授权数据。应该添加授权数据的行如下:

conn.setRequestProperty ("Authorization", "Basic " + encodedString);

和线

BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

还抛出IOException。

无论如何,如果有人可以建议对以上逻辑进行任何修复,以启用带有UrlConnection的POST授权,我将非常感激。

但是显然,它不能像预期的那样起作用,尽管如果将相同的逻辑用于GET请求,则一切正常。


阅读 277

收藏
2020-09-08

共1个答案

小编典典

这里有一个很好的例子。在下面的Powerlord正确的地方,您需要POST。HttpURLConnection

下面是执行此操作的代码,

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestProperty ("Authorization", encodedCredentials);

    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

    writer.write(data);
    writer.flush();
    String line;
    BufferedReader reader = new BufferedReader(new 
                                     InputStreamReader(conn.getInputStream()));
    while ((line = reader.readLine()) != null) {
      System.out.println(line);
    }
    writer.close();
    reader.close();

更改URLConnectionHttpURLConnection,使其成为POST请求。

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");

建议(…中的评论):

您可能还需要设置这些属性,

conn.setRequestProperty( "Content-type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "Accept", "*/*" );
2020-09-08