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
Your Java code doesn't process redirect response (HTTP code 302).
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'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 similar unanswered on Stackoverflow
This is how I went around it. Posting for others who might run into it.
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 Response Code :: 302
http://jenkinsurl1
POST Response Code :: 200
Related
all.
I'm trying to connect with a service to get a token by HttpsURLConnection(using groovy). The connection works ok, I'm getting an http code 200, but I'm getting the response with all strage characters.
responseCode: 200
Response Code : 200
Response Msg : OK
********** LINE: ‹ -̱
********** LINE: „0Ð^ðdë(‰&±¼ ›uD0’¤Pÿ]‰¶3óæ_WMHÄ)¹^a„NÊnÒDÂÒE…×ÞûóʪÞ!§ÈB>6¾Ý—1r|Þ·9rróý(‡¶}ÒD¡LCðPWçB9ÿý
Response: ‹ -̱„0Ð^ðdë(‰&±¼ ›uD0’¤Pÿ]‰¶3óæ_WMHÄ)¹^a„NÊnÒDÂÒE…×ÞûóʪÞ!§ÈB>6¾Ý—1r|Þ·9rróý(‡¶}ÒD¡LCðPWçB9ÿý
The charset i'm using is UTF-8. I've tried by postman and it works ok. I don't know what i'm doin wrong in my code.
connection.setDoOutput(true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(connection.getOutputStream());
outputStreamWriter.write(Parameters);
outputStreamWriter.flush();
int responseCode = connection.getResponseCode();
String responseMessage = connection.getResponseMessage();
logger.debug("responseCode: " + responseCode);
if(responseCode == 200){
logger.debug("Response Code : " + responseCode);
logger.debug("Response Msg : " + responseMessage);
BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = input.readLine()) != null) { //In this while i'm getting the response from service
response.append(inputLine);
logger.debug("\*\*\*\*\*\*\*\*\*\* LINE: " + inputLine);
}
input.close();
logger.debug("Response: " + response.toString()); //Here i'm printing the response in the log file
JSONObject jsonObj = new JSONObject(response.toString());
token = jsonObj.getString("access_token");
If it is not binary stream, but text this certainly seems like an encoding issue.
By using new InputStreamReader(connection.getInputStream()) you will use the default charset - does that match what is in the stream?
Try looking at what the URLConnection is reporting as the encoding/content type : https://docs.oracle.com/javase/7/docs/api/java/net/URLConnection.html
Then look how a library handles the conversion, for instance:
Apache's HttpClient BasicHttpClientResponseHandler delegates to EntityUtils, have a look at how that works: EntityUtils.java
But overall, why not save yourself the pain and use a library to do this? Several are discussed here: https://www.baeldung.com/java-http-response-body-as-string
Im trying to access to Google APIs using OAuth 2.0
but i always receive the http 400 when i try to get the token
I'm using Tomcat8 with Java SDK 8
And i don't know what is wrong.
private void sendPost(
final String code,
final String clientId,
final String clientSecret,
final String redirectUri,
final String grantType) throws Exception {
String url = "https://accounts.google.com/o/oauth2/token";
StringBuffer strb = new StringBuffer();
strb.append("code=" + code);
strb.append("&client_id=" + clientId);
strb.append("&client_secret=" + clientSecret);
strb.append("&redirect_uri=" + redirectUri);
strb.append("&grant_type=" + grantType);
String urlParameters = strb.toString();
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length", String.valueOf(urlParameters.length()));
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
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());
}
My output is the following it seems that all parameters are ok.
Sending 'POST' request to URL : https://accounts.google.com/o/oauth2/token
Post parameters : code=<code>.InoAg9JcLi0boiIBeO6P2m94pmoskwI&client_id=<clientid>.apps.googleusercontent.com&client_secret=<secret>&redirect_uri=http://localhost:8080/Oauth/connect&grant_type=authorization_code
Response Code : 400
you'd want to url-encode the parameters
I don't think Google supports redirect_uri's pointing to "localhost" anymore so that would suggest that you got the "code" on a different redirect_uri than the one presented on the token endpoint request
I have a question about making a POST request with Java, and since this is my first attempt at something of this magnitude, please bear with me. I am working on a third party application in Java to connect to a website and make POST requests. Am I doing this correctly? Here is what I have so far:
Website Code:
(This is the code the website has for "bumping a trade" which simply sends 2 pieces of data to a php file. The URL is http://cdn.dota2lounge.com/script/trades.js)
function bumpTrade(trade, code) {
$.ajax({
type: "POST",
url: "ajax/bumpTrade.php",
data: "trade=" + trade + "&code=" + code
});
}
My Java Code:
private void sendPost() throws Exception {
//String url = "https://www.cdn.dota2lounge.com/script/ajax/bumpTrade.php";
String url = "https://www.cdn.dota2lounge.com/script/ajax/bumpTrade.php";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "trade=96510389&code=94cebd9";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
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());
}
However I am receiving a connection timeout error when attempting to connect. I would be very grateful if someone could point me in the right direction!
The Java client code seems to be on the right track. But it looks like the URL in the code was the wrong URL.
Using the url "http://www.dota2lounge.com/ajax/bumpTrade.php" and HttpUrlConnection, I was able to get a 200 response (OK):
Sending 'POST' request to URL : http://www.dota2lounge.com/ajax/bumpTrade.php
Post parameters : trade=96510389&code=94cebd9
Response Code : 200
However nothing beyond that. Not sure of the API of the remote site but hopefully that's some help.
I seem to be getting a 404 error when sending a http post to a sinatra server. I am trying to make the server page the text I send to it, here's my code I think it may be something wrong with my server but I'm not sure:
private void sendInfo() throws Exception {
//make the string and URL
String url = "http://localhost";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
//send post
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'post' request to url: " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response code: " + responseCode);
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());
}
and here is the sinatra server (ruby):
require 'sinatra'
get '/' do
'hello mate'
end
get '/boo' do
'trololo'
end
Could your problem be realated to trying to use a HTTPS (instead of HTTP) connections? I am looing at the use of HttpsURLConnection.
Since you're sending your HTTP request via POST, shouldn't your sinatra server routes bet post instead of get? Would explain why you're getting a 404. Something like this should sort it out:
require 'sinatra'
post '/' do
'hello mate'
end
post '/boo' do
'trololo'
end
I am trying to implement the Twitter Search API V1.1
Please correct me if I am wrong.
I performed the below mentioned steps :
Step 1) Created an App in Twitter.
So I got the TWITTER_CONSUMER_KEY and TWITTER_CONSUMER_SECRETCODE.
Step 2) I encoded the concatenation of the above keys separated by ":" with the base UTF-8.
Step3 ) Get the bearer token with the above generated code.
Step4 ) Use the bearer code to get the Tweets on the relevance of a keyword.
I am stuck in Step 3,
where in I am getting the Response as::
Server returned HTTP response code: 400 for URL: https://api.twitter.com/oauth2/token
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at com.tcs.crm.socialCRM.action.TwitterIntegration.requestBearerToken(TwitterIntegration.java:74)
at com.tcs.crm.socialCRM.action.TwitterIntegration.getStatusSearch(TwitterIntegration.java:27)
at com.tcs.crm.socialCRM.action.TwitterIntegration.main(TwitterIntegration.java:103)
My code is ::
HttpsURLConnection connection = null;
PrintWriter outWriter = null;
BufferedReader serverResponse = null;
try
{
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "Search Tweets");
connection.setRequestProperty("Authorization", "Basic " + encodedCredentials);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
connection.setRequestProperty("Content-Length", "29");
connection.setUseCaches(false);
connection.setDoOutput( true );
logger.info("Point 1");
//CREATE A WRITER FOR OUTPUT
outWriter = new PrintWriter( connection.getOutputStream() );
logger.info("Point 2");
//SEND PARAMETERS
outWriter.println( "grant_type=client_credentials" );
outWriter.flush();
outWriter.close();
logger.info("Point 3");
//RESPONSE STREAM
serverResponse = new BufferedReader( new InputStreamReader( connection.getInputStream() ) );
JSONObject obj = (JSONObject)JSONValue.parse(serverResponse);
logger.info("The return string is "+obj.toString());
return obj.toString();
Please let me know how I can resolve this issue.
I had the same problem with the bearer token from Twitter. Also I test your same code and I received the error 403. After that I was creating my custom method to obtain the bearer token from twitter and I got the solution.
HttpClient httpclient = new DefaultHttpClient();
String consumer_key="YOUR_CONSUMER_KEY";
String consumer_secret="YOUR_CONSUMER_SECRET";
// Following the format of the RFC 1738
consumer_key=URLEncoder.encode(consumer_key, "UTF-8");
consumer_secret=URLEncoder.encode(consumer_secret,"UTF-8");
String authorization_header_string=consumer_key+":"+consumer_secret;
byte[] encoded = Base64.encodeBase64(authorization_header_string.getBytes());
String encodedString = new String(encoded); //converting byte to string
HttpPost httppost = new HttpPost("https://api.twitter.com/oauth2/token");
httppost.setHeader("Authorization","Basic " + encodedString);
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("grant_type", "client_credentials"));
httppost.setEntity(new UrlEncodedFormEntity(parameters));
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost, responseHandler);
Good luck!
The Twitter dev doc tells to give the "Content-Length":
https://dev.twitter.com/oauth/application-only
(see at "Example Result" below "Step 2: Obtain a bearer token")
However, in my case (with PHP), it works only if I remove "Content-Length".
I know this is rather late, but i found that the following worked for me (thanks #jctd_BDyn for the code to encode the key and secret for basic auth):
private String createBasicAuth() throws UnsupportedEncodingException {
String consumer_key="YOUR_CONSUMER_KEY";
String consumer_secret="YOUR_CONSUMER_SECRET";
// Following the format of the RFC 1738
consumer_key=URLEncoder.encode(consumer_key, "UTF-8");
consumer_secret=URLEncoder.encode(consumer_secret,"UTF-8");
String authorization_header_string=consumer_key+":"+consumer_secret;
byte[] encoded = Base64.encodeBase64(authorization_header_string.getBytes());
return new String(encoded); //converting byte to string
}
private HttpURLConnection createBearerTokenConnection() throws IOException {
URL url = new URL("https://api.twitter.com/oauth2/token");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
connection.setRequestProperty("Authorization", "Basic " + createBasicAuth());
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
String formData = "grant_type=client_credentials";
byte[] formDataInBytes = formData.getBytes("UTF-8");
OutputStream os = connection.getOutputStream();
os.write(formDataInBytes);
os.close();
log.info("Sending 'POST' request to URL : " + bearerTokenUrl);
return connection;
}
public Optional<BearerToken> getBearerToken() {
try {
HttpURLConnection connection = createBearerTokenConnection();
int responseCode = connection.getResponseCode();
log.info("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
if (responseCode == 200) {
// Transforming from JSON string to POJO
return transformer.toBearerToken(response.toString());
} else {
log.error("Unexpected response code with response " + response.toString());
}
} catch (IOException e) {
log.error(String.format("IO exception on POST to %s", bearerTokenUrl), e);
}
return Optional.empty();
}