比较Python和Java之间的HTTP PostJenkins 302/403响应代码

问题描述

我有一个简单的python代码,但无法在Java中运行 它也可以通过curl和postman起作用。 请帮忙

以下代码是python,相当简单明了。它返回200。

<!-- 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() function

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();
    
     // print result
     System.out.println(response.toString());
     } else {
       System.out.println("POST request not worked");
       }
 }

POST响应代码:: 302
POST请求不起作用

解决方法

您的Java代码不处理重定向响应(HTTP代码302)。

,

这与Jenkins的特性有关,而不是与Java有关。预期会出现302错误代码,Jenkins接受并完成所需的工作,并返回302。尽管我不知道python内部如何处理它(并调用两次?)并最终返回代码200

仅供参考,如果 setInstanceFollowedRedirects 设置为 true ,我得到403

jenkins bug
similar unanswered on Stackoverflow

这就是我的解决方法。发布给可能会遇到它的其他人。

 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); //calling the same function again with redirected url.
 }

POST响应代码:: 302
http:// jenkinsurl1
POST响应代码:: 200