0

我正在尝试通过 HTTPS 建立连接。我还将请求标头中的“授权”属性设置为基本,并相应地提供编码的身份验证字符串。

我检查了 Firefox 插件 HttpRequester 并且一切正常,这意味着我输入了 URL,选择“GET”作为请求方法,将授权添加到标题中,然后按提交后我返回一些只有经过适当授权的用户才能获得的 xml .

不幸的是,我既不能为您提供实际的身份验证信息,也不能为您提供 SSCCE 中的真实网址。但是,我可以告诉你,Auth 似乎有效,因为我收到了 200 响应。我还将 Auth 更改为错误的值,然后得到“需要 401 授权”响应。

实际上,似乎“?myparam = xyz”以某种方式被切断了,因为当我从url中删除此参数并再次使用Firefox HttpRequester进行测试时,我得到了与Java中相同的响应。

不幸的是,我无法访问“theirdomain.com”,所以我不知道服务器端发生了什么。但由于它适用于 Firefox HttpRequester,它也应该适用于 Java。

可能是什么原因?谢谢你的帮助!

编辑:我将网址更改为“ https://www.google.com/search?q=foo ”并评论了这一行:

//con.setRequestProperty("Authorization", auth);

我可以从返回的字符串中看到,谷歌收到了“foo”。因此,显然 Authorization 和 get 参数的组合似乎是问题所在,因为两者都可以正常工作。

SSCCE:

    import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

public class HttpRequest
{

    /**
     * @param args
     */
    public static void main(final String[] args)
    {
        System.out.println("start request");
        final String urlString = "https://theirdomain.com/foo/bar/bob?myparam=xyz";
        final String auth = "Basic XyzxYzxYZxYzxyzXYzxY==";

        HttpsURLConnection con;
        try
        {

            final URL url = new URL(urlString);

            con = (HttpsURLConnection) url.openConnection();
            con.setRequestProperty("Authorization", auth);
            con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");

            con.setRequestMethod("GET");
            //            con.setDoOutput(true);
            con.connect();
            final int responseCode = con.getResponseCode();
            if (responseCode != 200)
                System.out.println("Server responded with code " + responseCode + " " + con.getResponseMessage());
            else
            {
                System.out.println("Starting to read...");

                final InputStream inStream = con.getInputStream();
                final ByteArrayOutputStream baos = new ByteArrayOutputStream();

                int c;

                while (inStream != null && (c = inStream.read()) != -1)
                {
                    baos.write(c);
                }

                System.out.println(new String(baos.toByteArray()));
            }
        }
        catch (final IOException e)
        {
            System.out.println("could not open an HTTP connection to url: " + urlString);
            e.printStackTrace();
        }
        finally
        {
            System.out.println("end request");
        }
    }

}
4

1 回答 1

0

您是否尝试过添加 con.setRequestProperty("myparam", "xyz");到您的代码中?

于 2013-12-03T13:59:38.080 回答