Java equivalent HTTP post method for given curl code - java

What is the Java Equivalent Post method code for the curl?
curl -X POST https://api.twilio.com/2010-04-
01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages.json \
--data-urlencode "From=+15017122661" \
--data-urlencode "Body=body" \
--data-urlencode "To=+15558675310" \
-u ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token
This is my code:
String message = "Body=" + "This is your message";
String sender = "&From=" + "+14708657743";
String numbers = "&To=" + "+919943666843";
String auth = "ACb3739c0a4bf6d2cc5495a8ff3c545ea9:9ae02782844f6349d24a36bf922746b2";
auth = Base64.getEncoder().encodeToString(auth.getBytes());
String data = message + sender + numbers+ auth;
URL url = new URL("https://api.twilio.com/2010-04-01/Accounts/ACb3739c0a4bf6d2cc5495a8ff3c545ea9/Messages.json?"+URLEncoder.encode(data,"UTF-8"));
System.out.println(url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Basic " + auth);
Where did I go wrong? Can anyone suggest the correct code?

Related

Convert Curl -G to java code

I need to transform this curl to java code
curl -G \
-u "{user}":"{pass}" \
-d "version=2018-03-16" \
-d "the msg" \
-d "features=entities" \
-d "entities.model={modelID}" \
"https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze"
and my java code is something like that
URL url = new URL(uri.toString());
HttpURLConnection handle = (HttpURLConnection) url.openConnection();
String userpass = "{user}:{pass}";
new Base64();
String basicAuth = "Basic " + new String(Base64.encode(userpass.getBytes()));
handle.setRequestMethod("POST");
handle.setRequestProperty("Content-Type", "application/json");
handle.setRequestProperty("Authorization", basicAuth);
handle.setRequestProperty("version", "2018-03-16");
handle.setRequestProperty("text", params.getParameterString());
handle.setRequestProperty("features", "entities");
handle.setRequestProperty("entities.model", wksModel);
handle.setDoOutput(true);
This gives me error 400 so you do not know where my mistake, I hope you can help me

How to use cURL requests in Java

I am trying to get some authorisation codes from Spotify. I use the athorisation flow described here: https://developer.spotify.com/web-api/authorization-guide/#authorization-code-flow. Now I am stuck at number four: "Your application requests refresh and access tokens" I have to ask Spotify for accses_token and refresh_token with an cURL request. The cURL request has to be something like this:
curl -H "Authorization: Basic ZjM...zE=" -d grant_type=authorization_code -d code=MQCbtKe...44KN -d redirect_uri=http://localhost/codeAuslesen.php https://accounts.spotify.com/api/token
I tryed to achieve this with :
String clientId = <client_Id>;
String clientSecret = <clientSecret>;
String getTokenUrl = "https://accounts.spotify.com/api/token";
String encodeString = clientId + ":" + clientSecret;
String basicAuth = "Basic " + Base64.getEncoder().encode(encodeString.getBytes());
String url = getTokenUrl;
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", basicAuth);
conn.setRequestProperty("grant_type", "authorization_code");
conn.setRequestProperty("code", code);
conn.setRequestProperty("redirect_uri", redirectUri);
try {
BufferedReader tokenReader = new BufferedReader(new InputStreamReader(conn.getInputStream())); //Exception points here
while((tokenLine = tokenReader.readLine()) != null) {
tokenResult += tokenLine;
}
tokenReader.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(tokenResult);
}
I am just getting this Exception:
java.io.IOException: Server returned HTTP response code: 400 for URL: https://accounts.spotify.com/api/token
Does someone see what I am doing wrong?

How to make same cURL request in android java?

I cannot understand request below for cURL:
curl -X POST -u "client_id:secret" \
https://bitbucket.org/site/oauth2/access_token -d grant_type=password \
-d username={username} -d password={password}
How can I make same request in java (Android)?
Now, I try so:
String auth = vcs.getKey() + ":" + vcs.getSecret();
byte[] authEncBytes = Base64.encode(auth.getBytes(), Base64.DEFAULT);
String authStringEnc = new String(authEncBytes);
URL url = new URL("https://bitbucket.org/site/oauth2/access_token");
HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
connection.setRequestMethod("POST");
connection.setRequestProperty("grant_type", "password");
connection.setRequestProperty("username", mLogin);
connection.setRequestProperty("password", mPassword);
But it doesn't work.
You are passing the post parameters with at request header. Remove the last three and replace with below:
String params = "grant_type=password&username=xyz&password="+ java.net.URLEncoder.encode("urp&^!ass", "UTF-8");
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8"));
writer.write(params);
writer.flush();
writer.close();
os.close();
int responseCode = connection.getResponseCode();

write a post curl in java

I am trying to write a post curl in java.
my curl is:
curl -X PUT -u username:password http://localhost:1234/api/2.0/data1/include/value1
I wrote in java:
String stringUrl = "http://localhost:1234/api/2.0/data1/include/value1";
URL url = new URL(stringUrl);
URLConnection uc = url.openConnection();
uc.setRequestProperty("X-Requested-With", "Curl");
String userpass = "username" + ":" + "password";
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
uc.setRequestProperty("Authorization", basicAuth);
InputStreamReader inputStreamReader = new InputStreamReader(uc.getInputStream());
Interestingly, it did not give any error but nothing happened and value1 did not add to input 1 so it means the curl post that I wrote did not do anything. Can anyone be kind enough to help me convert the above post curl request to java code?
For better invoking HTTP methods use Apache HttpClient.
Here is a nice overview how to start with get and post method:
http://www.vogella.com/tutorials/ApacheHttpClient/article.html
It looks like you forgot to call: uc.setDoOutput(true); before trying to set any http headers with setRequestProperty() See: http://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html

Java cURL alternative with HttpURLConnection

I was asked to port a PHP module I was writing to Java. I was previously using PHP's native cURL library, now trying to achieve the same action with HttpURLConnection.
Here's the call I want to do with cURL:
curl -u 'ExactID:Password' \
-H 'Content-Type: application/json; charset=UTF-8' \
-H 'Accept: application/json' \
-d '{
"transaction_type":"00",
"amount":"15.75",
"cardholder_name":"PaulTest",
"transarmor_token":"3000",
"credit_card_type":"Visa",
"cc_expiry":"0016",
}' \
https://api.demo.globalgatewaye4.firstdata.com/transaction/v11
Here's what I have in Java, which returns a HTTP 400 error. Any ideas?
public static void main(String[] args) {
URL url = new URL("https://api.demo.globalgatewaye4.firstdata.com/transaction/v11");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
String userpass = "ExactID" + ":" + "Password";
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
conn.setRequestProperty ("Authorization", basicAuth);
JSONObject obj = new JSONObject();
obj.put("transaction_type", "00");
obj.put("amount", "10");
obj.put("cardholder_name", "PaulTest");
obj.put("transarmor_token", "3000");
obj.put("cc_expiry", "0016");
obj.put("credit_card_type", "Visa");
String input = obj.toString();
System.out.println(input);
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "+ conn.getResponseCode() + conn.getResponseMessage());
}
One ambiguity in your java code is on string to byte array encoding. By default java will use your default platform encoding, but it's a good practice to express it explicitly because it often lead to hard to track bug
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes("ISO-8859-1")));
To be sure also check the encoded base 64 value generated by java on curl by using
-H 'Authorization: Basic ....`
Instead of -u
Also I'd try to cast the created URLConnection to HttpsURLConnection. Thay may/not make difference
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
After tinkering around, I made two mistakes:
For this POST method, basic authentication was not required. The user & pw goes into the JSON body along with the other parameters.
Also, my "transarmor_token" field needed to be 16 digits.
Conclusion: HttpURLConnection is a great cURL alternative. Forget about using the curl-java binding.
Thanks!

Categories