Java:如何使用UrlConnection进行带有授权的POST请求?

38

我想向一个需要身份认证的服务器生成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请求使用相同的逻辑一切正常,但它并没有像应该的那样工作。

8个回答

50

这里有一个很好的示例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();

URLConnection更改为HttpURLConnection,以进行POST请求。
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");

建议(在评论中):

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

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

2
这是一个GET请求,没有问题。 - Niko Gamulin
3
授权方面没有太大的区别。 - Adeel Ansari
4
如果您来到这里是想了解如何进行“post bit”的操作:( - David Newcomb
这个答案不正确:答案是:https://dev59.com/n3I-5IYBdhLWcg3wEEHu#2165000 - Bob
当我尝试上面的代码时,它没有起作用。我不得不在连接上添加以下内容:uc.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); uc.setRequestProperty("Accept", "*/*"); - Ray Kiddy
显示剩余7条评论

15

我在代码中没有看到你指定这是一个POST请求的地方。不过,你需要使用java.net.HttpURLConnection来实现。

事实上,我强烈建议使用HttpURLConnection代替URLConnection,并添加 conn.setRequestMethod("POST");来查看是否仍然有问题。


1
这是正确的答案。您不能使用URLConnection进行POST请求,必须使用HttpURLConnection。 - Bob

6

进行oAuth身份验证以连接到外部应用程序(INSTAGRAM)第三步“在收到代码后获取令牌”,下面的代码对我有效。

值得注意的是,我使用一些localhost URL并配置了名为“web.xml”中的回调servlet,并注册了回调URL:例如localhost:8084/MyAPP/docs/insta/callback

但是,在成功完成身份验证步骤之后,尝试使用相同的外部网站“INSTAGRAM”进行GET标记或多媒体以使用初始方法检索JSON数据失败。通过我的servlet来使用类似于 e.g. api.instagram.com/v1/tags/MYTAG/media/recent?access_token=MY_TOKEN的URL进行GET只有这里找到的方法有效。

感谢所有贡献者

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

2

发送POST请求时调用:

        connection.setDoOutput(true); // Triggers POST.

如果您想在请求中发送文本,请使用以下方法:

        java.io.OutputStreamWriter wr = new java.io.OutputStreamWriter(connection.getOutputStream());
        wr.write(textToSend);
        wr.flush();

connection.setDoOutput(true);不会触发POST请求。添加这行代码System.out.println(((HttpURLConnection)connection).getRequestMethod());,你将会读到GET - Würgspaß

1
我今天遇到了这个问题,这里发布的所有解决方案都没有用。然而,这里发布的代码适用于POST请求:
// HTTP POST request
private void sendPost() throws Exception {

    String url = "https://selfsolve.apple.com/wcResults.do";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    //print result
    System.out.println(response.toString());

}

事实证明,问题并不在于授权。在我的情况下,这是一个编码问题。我需要的内容类型是application/json,但根据Java文档:
static String encode(String s, String enc)
Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme.

encode函数将字符串转换为application/x-www-form-urlencoded格式。

如果您没有设置Content-Type,可能会收到415 Unsupported Media Type错误。如果将其设置为application/json或任何不是application/x-www-form-urlencoded的内容,则会收到IOException。要解决此问题,只需避免使用encode方法。

对于这种特定情况,以下方法应该可行:

String data = "product[title]=" + title +
                "&product[content]=" + content + 
                "&product[price]=" + price.toString() +
                "&tags=" + tags;

关于为什么创建缓冲读取器时代码会中断的另一个小提示是,POST请求实际上只有在调用conn.getInputStream()时才会执行。


1
在API 22中,基本名称值对的使用已被弃用,而应该使用HASMAP。要了解有关HasMap的更多信息,请访问此处有关hasmap开发者.android的更多信息
package com.yubraj.sample.datamanager;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.yubaraj.sample.utilities.GeneralUtilities;


import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

/**
 * Created by yubraj on 7/30/15.
 */
public class ServerRequestHandler {
    private static final String TAG = "Server Request";
    OnServerRequestComplete listener;

    public ServerRequestHandler (){

    }
    public void doServerRequest(HashMap<String, String> parameters, String url, int requestType, OnServerRequestComplete listener){

        debug("ServerRequest", "server request called, url  = " + url);
        if(listener != null){
            this.listener = listener;
        }
        try {
            new BackgroundDataSync(getPostDataString(parameters), url, requestType).execute();
            debug(TAG , " asnyc task called");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    public void doServerRequest(HashMap<String, String> parameters, String url, int requestType){
        doServerRequest(parameters, url, requestType, null);
    }

    public interface OnServerRequestComplete{
        void onSucess(Bundle bundle);
        void onFailed(int status_code, String mesage, String url);
    }

    public void setOnServerRequestCompleteListener(OnServerRequestComplete listener){
        this.listener = listener;
    }

    private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, String> entry : params.entrySet()){
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }

    class BackgroundDataSync extends AsyncTask<String, Void , String>{
        String params;
        String mUrl;
        int request_type;

        public BackgroundDataSync(String params, String url, int request_type){
            this.mUrl = url;
            this.params = params;
            this.request_type = request_type;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... urls) {
            debug(TAG, "in Background, urls = " + urls.length);
            HttpURLConnection connection;
                debug(TAG, "in Background, url = " + mUrl);
                String response = "";
                switch (request_type) {
                    case 1:
                        try {
                            connection = iniitializeHTTPConnection(mUrl, "POST");
                            OutputStream os = connection.getOutputStream();
                            BufferedWriter writer = new BufferedWriter(
                                    new OutputStreamWriter(os, "UTF-8"));
                            writer.write(params);
                            writer.flush();
                            writer.close();
                            os.close();
                            int responseCode = connection.getResponseCode();
                            if (responseCode == HttpsURLConnection.HTTP_OK) {
                           /* String line;
                            BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
                            while ((line=br.readLine()) != null) {
                                response+=line;
                            }*/
                                response = getDataFromInputStream(new InputStreamReader(connection.getInputStream()));
                            } else {
                                response = "";
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        break;
                    case 0:
                        connection = iniitializeHTTPConnection(mUrl, "GET");

                        try {
                            if (connection.getResponseCode() == connection.HTTP_OK) {
                                response = getDataFromInputStream(new InputStreamReader(connection.getInputStream()));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            response = "";
                        }
                        break;
                }
                return response;


        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if(TextUtils.isEmpty(s) || s.length() == 0){
                listener.onFailed(DbConstants.NOT_FOUND, "Data not found", mUrl);
            }
            else{
                Bundle bundle = new Bundle();
                bundle.putInt(DbConstants.STATUS_CODE, DbConstants.HTTP_OK);
                bundle.putString(DbConstants.RESPONSE, s);
                bundle.putString(DbConstants.URL, mUrl);
                listener.onSucess(bundle);
            }
            //System.out.println("Data Obtained = " + s);
        }

        private HttpURLConnection iniitializeHTTPConnection(String url, String requestType) {
            try {
                debug("ServerRequest", "url = " + url + "requestType = " + requestType);
                URL link = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) link.openConnection();
                conn.setRequestMethod(requestType);
                conn.setDoInput(true);
                conn.setDoOutput(true);
                return conn;
            }
            catch(Exception e){
                e.printStackTrace();
            }
            return null;
        }

    }
    private String getDataFromInputStream(InputStreamReader reader){
        String line;
        String response = "";
        try {

            BufferedReader br = new BufferedReader(reader);
            while ((line = br.readLine()) != null) {
                response += line;

                debug("ServerRequest", "response length = " + response.length());
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return response;
    }

    private void debug(String tag, String string) {
        Log.d(tag, string);
    }
}

当需要从服务器获取数据时,只需像这样调用函数,无论是通过post还是get:

HashMap<String, String>params = new HashMap<String, String>();
                    params.put("action", "request_sample");
                    params.put("name", uname);
                    params.put("message", umsg);
                    params.put("email", getEmailofUser());
                    params.put("type", "bio");
dq.doServerRequest(params, "your_url", DbConstants.METHOD_POST);
                    dq.setOnServerRequestCompleteListener(new ServerRequestHandler.OnServerRequestComplete() {
                        @Override
                        public void onSucess(Bundle bundle) {
                            debug("data", bundle.getString(DbConstants.RESPONSE));
                                                    }

                        @Override
                        public void onFailed(int status_code, String mesage, String url) {
                            debug("sample", mesage);

                        }
                    });

现在已经完成。享受吧!如果发现任何问题,请评论。

0

HTTP授权在GET和POST请求之间没有区别,因此我首先会假设其他地方出了问题。建议不要直接设置Authorization头,而是使用java.net.Authorization类,但我不确定它是否能解决您的问题。也许您的服务器以某种方式配置为要求不同于“basic”的授权方案用于POST请求?


很棒,我从来不知道有这个类。然而,这个类是抽象的,所以他实际上需要一个实现类。 - Powerlord
当然,您需要实现一个特定于应用程序的方式来获取凭据。在交互式应用程序中,您可能需要弹出对话框等方式。 - jarnbjo

-1
我正在寻找关于如何进行POST请求的信息。我需要指定我的请求是一个POST请求,因为我正在使用只使用POST方法的RESTful Web服务,如果请求不是POST,则在尝试进行请求时会收到HTTP错误405。我保证我的代码没有问题,我创建了一个通过GET请求调用的Web服务方法,并将我的应用程序指向消耗该Web服务方法,它可以正常工作。 我的代码如下:
    URL server = null;
    URLConnection conexion = null;
    BufferedReader reader = null;
    server = new URL("http://localhost:8089/myApp/resources/webService");
    conexion = server.openConnection();
    reader = new BufferedReader(new InputStreamReader(server.openStream()));
    System.out.println(reader.readLine());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接