Java:如何使用UrlConnection通过授权发布请求?

Nik*_*lin 34 java post authorization urlconnection httpconnection

我想向需要身份验证的服务器生成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();
    } 
}
Run Code Online (Sandbox Code Playgroud)

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

conn.setRequestProperty ("Authorization", "Basic " + encodedString);
Run Code Online (Sandbox Code Playgroud)

和线

BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
Run Code Online (Sandbox Code Playgroud)

也会抛出IOException.

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

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

Ade*_*ari 42

这里有一个很好的例子.对于你需要的POST ,Powerlord下面做对了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();
Run Code Online (Sandbox Code Playgroud)

更改URLConnectionHttpURLConnection,以使其成为POST请求.

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
Run Code Online (Sandbox Code Playgroud)

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

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

conn.setRequestProperty( "Content-type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "Accept", "*/*" );
Run Code Online (Sandbox Code Playgroud)

  • 如果你来这里寻找如何做位置:( (4认同)
  • 在授权方面没有太大区别. (3认同)
  • 这是GET请求,这不是问题. (2认同)

Pow*_*ord 12

我没有在代码中看到您指定这是POST请求的任何地方.然后,你需要java.net.HttpURLConnection做到这一点.

事实上,我强烈建议使用HttpURLConnection而不是URLConnection,conn.setRequestMethod("POST");看看它是否仍然给你带来问题.


小智 5

对外部应用(INSTAGRAM)进行oAuth身份验证步骤3“收到代码后获取令牌”只有下面的代码对我有用

值得一提的是,它对我来说也可以使用某些本地主机URL,并将其配置为名称为“ call。in web.xml的回调servlet,并注册了回调URL:例如localhost:8084 / MyAPP / docs / insta / callback

但是,成功完成身份验证步骤后,无法使用相同的外部站点“ INSTAGRAM”执行GET的标签或使用初始方法来获取JSON数据的MEDIA。里面我的servlet做GET使用URL例如像api.instagram.com/v1/tags/MYTAG/media/recent?access_token=MY_TOKEN唯一方法发现这里的工作

感谢所有贡献者

        URL url = new URL(httpurl);
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("client_id", id);
        params.put("client_secret", secret);
        params.put("grant_type", "authorization_code");
        params.put("redirect_uri", redirect);
        params.put("code", code);  // your INSTAGRAM code received 
        Set set = params.entrySet();
        Iterator i = set.iterator();
        StringBuilder postData = new StringBuilder();
        for (Map.Entry<String, String> param : params.entrySet()) {
            if (postData.length() != 0) {
                postData.append('&');
            }
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }
        byte[] postDataBytes = postData.toString().getBytes("UTF-8");

        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
        conn.setDoOutput(true);
        conn.getOutputStream().write(postDataBytes);
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        StringBuilder builder = new StringBuilder();
        for (String line = null; (line = reader.readLine()) != null;) {
            builder.append(line).append("\n");
        }
        reader.close();
        conn.disconnect();
        System.out.println("INSTAGRAM token returned: "+builder.toString());
Run Code Online (Sandbox Code Playgroud)