比较Python和Java之间的HTTP Post(Jenkins 302/403响应代码)。

huangapple go评论71阅读模式
英文:

compare HTTP Post between Python and Java (Jenkins 302/403 response code)

问题

以下是翻译好的内容:

我有一个简单的Python代码可以工作但我无法在Java中使其工作
它还可以通过curl和postman工作
请帮忙

以下是Python代码非常简单明了返回200

```python
<!-- language: lang-python -->

import requests
params = (
    ('member', 'xxx'),
)

response = requests.post('http://jenkinsurl1/submitRemoveMember', params=params, auth=('user', 'notbase64encodedtoken'))
print(response)

返回 200

以下是Java代码,我无法找到一个简单明了的方法在Java中实现这个。

<!-- language: lang-java -->

// main() 函数

String auth = "user" + ":" + "notbase64encodedtoken";
byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(StandardCharsets.UTF_8));
final String POST_PARAMS = "member=xxxx";
MyPOSTRequest(POST_PARAMS, encodedAuth, "http://jenkinsurl1/submitRemoveMember");


public static void MyPOSTRequest(String Parameters, byte[] encodedAuth, String POST_URL) throws IOException {

URL obj = new URL(POST_URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
byte[] postData = Parameters.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setInstanceFollowRedirects(false);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("charset", "utf-8");
con.setRequestProperty("Content-Length", Integer.toString(postDataLength));
String authHeaderValue = "Basic " + new String(encodedAuth);
con.setRequestProperty("Authorization", authHeaderValue);
con.setUseCaches(false);

try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
    wr.write(postData);
    wr.flush();
}
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);

if (responseCode == HttpURLConnection.HTTP_OK) { // success
    BufferedReader in = new BufferedReader(new InputStreamReader(
            con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

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

    // 打印结果
    System.out.println(response.toString());
} else {
    System.out.println("POST 请求未成功");
}
}

POST Response Code :: 302

POST 请求未成功


<details>
<summary>英文:</summary>
I have a simple python code working but I am unable to get it to work in Java
it also works via curl and postman.
Please help
The following code is python and is fairly simple and straightforward. it returns 200.
&lt;!-- language: lang-python --&gt;
import requests
params = (
(&#39;member&#39;, &#39;xxx&#39;),
)
response = requests.post(&#39;http://jenkinsurl1/submitRemoveMember&#39;, params=params, auth=(&#39;user&#39;, &#39;notbase64encodedtoken&#39;))
print(response)
&gt; **Returns 200**
The following code is in java and I am unable to find a simple and straightforward way to do this in java.
&lt;!-- language: lang-java --&gt;
//main() function
String auth = &quot;user&quot; + &quot;:&quot; + &quot;notbase64encodedtoken&quot;;
byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(StandardCharsets.UTF_8));
final String POST_PARAMS = &quot;member=xxxx&quot;;
MyPOSTRequest(POST_PARAMS,encodedAuth,&quot;http://jenkinsurl1/submitRemoveMember&quot;);
public static void MyPOSTRequest(String Parameters, byte[] encodedAuth, String POST_URL) throws IOException {
URL obj = new URL(POST_URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
byte[] postData       = Parameters.getBytes( StandardCharsets.UTF_8 );
int    postDataLength = postData.length;
con.setRequestMethod(&quot;POST&quot;);
con.setDoOutput( true );
con.setInstanceFollowRedirects( false );
con.setRequestProperty( &quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;);
con.setRequestProperty( &quot;charset&quot;, &quot;utf-8&quot;);
con.setRequestProperty( &quot;Content-Length&quot;, Integer.toString( postDataLength ));
String authHeaderValue = &quot;Basic &quot; + new String(encodedAuth);
con.setRequestProperty(&quot;Authorization&quot;, authHeaderValue);
con.setUseCaches( false );
try( DataOutputStream wr = new DataOutputStream( con.getOutputStream())) {
wr.write( postData );
wr.flush();
}
int responseCode = con.getResponseCode();
System.out.println(&quot;POST Response Code :: &quot; + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
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());
} else {
System.out.println(&quot;POST request not worked&quot;);
}
}
&gt; **POST Response Code :: 302**
&gt; &lt;br&gt;**POST request not worked**
</details>
# 答案1
**得分**: 0
你的Java代码未处理重定向响应(HTTP代码302)。
<details>
<summary>英文:</summary>
Your Java code doesn&#39;t process redirect response (HTTP code 302).
</details>
# 答案2
**得分**: 0
这更多是与Jenkins的特点有关,而不是与Java有关。302错误代码是预期的,Jenkins接受并执行所需的工作,然后返回302。尽管我不知道Python如何在内部处理它(并调用两次?),最终返回代码200。
如果**setInstanceFollowedRedirects**设置为**true**,我会收到403错误。
[Jenkins错误][1]   &lt;br&gt;[在Stackoverflow上类似的问题没有答案][2]
这是我解决的方法。为了帮助其他可能遇到此问题的人。

int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);

if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP) { //MOVED_TEMP
String location = con.getHeaderField("Location");
System.out.println(location);
MyPOSTRequest(Parameters, encodedAuth, location); //使用重定向的URL再次调用相同的函数。
}


&gt; **POST Response Code :: 302
&gt; &lt;br&gt; http://jenkinsurl1
&gt; &lt;br&gt; POST Response Code :: 200**
[1]: https://issues.jenkins-ci.org/browse/JENKINS-53869
[2]: https://stackoverflow.com/questions/49194812/rest-execution-fails-with-status-code-302
<details>
<summary>英文:</summary>
This was more to do with Jenkins idiosyncrasies than to do with java. The 302 error code was expected and Jenkins accepts and does the work required and returns with 302. Although I don&#39;t know how python deals with it internally (and calls two times?) and returns code 200 eventually
FYI if **setInstanceFollowedRedirects** is set to **true**, I get a 403
[jenkins bug][1]   &lt;br&gt;[similar unanswered on Stackoverflow ][2]
This is how I went around it. Posting for others who might run into it.
int responseCode = con.getResponseCode();
System.out.println(&quot;POST Response Code :: &quot; + responseCode);
if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP) { //MOVED_TEMP
String location = con.getHeaderField(&quot;Location&quot;);
System.out.println(location);
MyPOSTRequest(Parameters, encodedAuth, location); //calling the same function again with redirected url.
}
&gt; **POST Response Code :: 302
&gt; &lt;br&gt; http://jenkinsurl1
&gt; &lt;br&gt; POST Response Code :: 200**
[1]: https://issues.jenkins-ci.org/browse/JENKINS-53869
[2]: https://stackoverflow.com/questions/49194812/rest-execution-fails-with-status-code-302
</details>

huangapple
  • 本文由 发表于 2020年8月12日 18:40:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/63374807.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定