java - 将curl请求转换为HttpURLConnection

标签 java authentication curl https

我正在尝试实现一个首先登录并执行一些工作的客户端。 这是我的 curl 请求:

curl -v https://api.example.com/api-token-auth/ \
   -H "Accept: application/json" \
   -d "username=myusername&password=mypassword"

我想将它转换成java代码。这是我尝试过的:

HttpURLConnection conn;
URL obj = new URL("https://api.example.com/api-token-auth/");
URL obj = new URL(quoteURL);
conn = (HttpURLConnection) obj.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
String userpass = "username=myusername" + "&" + "password=mypassword";
String basicAuth =  new String(Base64.getEncoder().encode(userpass.getBytes()));
conn.setRequestProperty("Authorization", basicAuth);
conn.setRequestProperty( "Accept", "*/*" );
conn.setRequestProperty( "Accept-Encoding", "gzip, deflate" );
conn.setRequestProperty( "Accept-Language", "en;q=1, fr;q=0.9, de;q=0.8,ja;q=0.7, nl;q=0.6, it;q=0.5" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded; charset=utf-8" );
conn.setRequestProperty( "API-Version", "1.3.0" );
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty( "Accept", "*/*" );
conn.setRequestProperty("User-Agent", "Mozilla/5.0");
conn.connect();
InputStreamReader inputStreamReader = new InputStreamReader(conn.getInputStream());
BufferedReader in = new BufferedReader(inputStreamReader);
String inputLine;
StringBuffer response = new StringBuffer();

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

然后我收到此错误:

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL: https://api.example.com/api-token-auth/
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1839)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1440)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)

我尝试了几种可能的解决方案,但没有成功。我找不到我做错了什么。

最佳答案

您的curl请求实际上并没有执行HTTP basicAuth(这就是您的示例代码试图执行的操作) - 它只是将-d参数发布到服务器(作为url编码的主体)

所以

  1. 摆脱所有 setRequestProperty() 内容(不需要)
  2. 使用 con.setContentType("application/x-www-form-urlencoded") [这可以说更干净一点]
  3. 将用户密码字符串写入 con.getOutputStream() [无需进行 Base64 编码...同样,这与 http basicAuth 无关]

例如,您的curl 命令发出以下 HTTP 请求

POST /api-token-auth/ HTTP/1.1
Host: api.example.com
User-Agent: curl/7.49.1
Accept: application/json
Content-Length: 39
Content-Type: application/x-www-form-urlencoded

username=myusername&password=mypassword

下面的 Java 程序将执行几乎完全相同的请求

public class SO {
public static void main(String[] args) throws Exception {
    String rsp = curl("http://axrsgpar0019:13080/api-token-auth/", "application/json", "username=myusername&password=mypassword");
}
public static String curl(String url, String accepts, String minusD) throws Exception {
    HttpURLConnection con = (HttpURLConnection)new URL(url).openConnection();
    con.setDoOutput(true);
    con.setRequestProperty("Accept", accepts);
    con.setRequestProperty("Content-Type",  "application/x-www-form-urlencoded");
    con.getOutputStream().write(minusD.getBytes());
    con.getOutputStream().close();

    ByteArrayOutputStream rspBuff = new ByteArrayOutputStream();
    InputStream rspStream = con.getInputStream();

    int c;
    while ((c = rspStream.read()) > 0) {
        rspBuff.write(c);
    }
    rspStream.close();

    return new String(rspBuff.toByteArray());
}
}

生成以下 HTTP 请求(唯一的区别是 User-Agent 和 keep-alive..这应该是微不足道的)

POST /api-token-auth/ HTTP/1.1
Accept: application/json
Content-Type: application/x-www-form-urlencoded
User-Agent: Java/1.8.0_91
Host: api.example.com
Connection: keep-alive
Content-Length: 39

username=myusername&password=mypassword

关于java - 将curl请求转换为HttpURLConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39862657/

相关文章:

php - Symfony 2.8 -> 3.4 升级 IsGranted ('IS_AUTHENTICATED_ANONYMOUSLY' ) 引发错误

java - 允许一次登录一台设备

curl - 从 curl 命令在 Keycloak 上创建用户

linux - 在 Linux 中发送带有 JSON 数据的 POST 请求

php - 通过 PHP 的 curl over ftps 连接删除文件是回显目录内容

java - Xpath、Java 和变量

java - JFrame 组合框事件键...帮助

java - 在 Camel 路由中访问 HTTPSession

java - 如何解析我的 json 结果

selenium - 如何构建关键字,这样我就不必在使用 seleniumlibrary 的机器人框架测试用例中运行登录到 Web 的所有功能?