Java:如何使用 UrlConnection 发布授权请求? [英] Java: how to use UrlConnection to post request with authorization?

查看:53
本文介绍了Java:如何使用 UrlConnection 发布授权请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to generate POST request to a server which requires authentication. I tried to use the following method:

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();
    } 
}

但是服务器没有收到授权数据.应该添加授权数据的行如下:

but the server doesn't receive the authorization data. The line which is supposed to add authorization data is the following:

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

和线

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

也会抛出一个 IOException.

also throws an IOException.

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

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.

但显然它不能正常工作,尽管如果对 GET 请求使用相同的逻辑,一切正常.

but obviously it doesn't work as it is supposed to although if the same logic is used for GET request everything works fine.

推荐答案

一个很好的 示例找到这里.Powerlord 做对了,下面,对于 POST 你需要 HttpURLConnection,而是.

A fine example found here. Powerlord got it right, below, for POST you need HttpURLConnection, instead.

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

Below is the code to do that,

    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();

URLConnection改为HttpURLConnection,使其成为POST请求.

Change URLConnection to HttpURLConnection, to make it POST request.

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

建议(...在评论中):

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

You might need to set these properties too,

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

这篇关于Java:如何使用 UrlConnection 发布授权请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆