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.
<!-- language: lang-python -->
import requests
params = (
('member', 'xxx'),
)
response = requests.post('http://jenkinsurl1/submitRemoveMember', params=params, auth=('user', 'notbase64encodedtoken'))
print(response)
Returns 200
The following code is in java and I am unable to find a simple and straightforward way to do this in 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 Response Code :: 302
POST request not worked