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!
Related
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?
I have a java application with this code :
URL url = new URL("http://myurl/");
HttURLConnection connection = (HttURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutplut(true);
connection.setRequestProperty("Content-Type", "application/json");
BufferedWriter buffer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
buffer.write("{\"foo:\"0}");
buffer.flush();
I just want to do the samething in my navigatour URL bar.
Edit
I found a tool to modifier headers. Here a screenshoot of the dev tool when I load my page.
Now where did I put my Json object?
If you need to send JSON data to your URL your code should be like this,
URL url = new URL("http://myurl/");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
String input = "{\"foo\":\"bar\"}";
OutputStream ous = con.getOutputStream();
ous.write(input.getBytes());
ous.flush();
if (con.getResponseCode() != HttpURLConnection.HTTP_OK)
{
throw new RuntimeException("Failed : HTTP error code : " + con.getResponseCode());
}else
{
BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null)
{
System.out.println(output);
}
}
con.disconnect();
If you need GET Method then you can place this,
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
If you need to send Request Body with the URL you can use CURL. And also you can use POSTMAN. By using this you can send requests and receive the response.
CURL will be like this,
curl -v -H "Content-Type: application/json" -X POST \
-d '{\"foo\":\"bar\"}' http://myurl/
You can use Firefox to perform what you need, Read the 2nd answer.
I'm trying to implement an API with a GraphQL query in my android app but having trouble with how to go about converting the cURL to java. I'm relatively new to programming so I've been trying to follow tutorials and questions on here but having no luck for the past few days.
Basically the cURL command sends a GraphQL query and returns a json which I'd like to extract specific data from.
The cURL command is as follows
curl -v 'https://api.url/' \
-H 'content-type: application/json' \
-H 'accept: application/json' \
-H 'x-api-key: <YOUR_API_KEY>' \
--data-binary '{"query":"{ Search(query: \"searchVariable\") {items{description} } }","variables":"{}","operationName":null}'
When I run this in the terminal it returns a json string. I would like to return this in my app and extract data from the json. I think I can do this using a json object but cannot get the data in the first place
Here is one method I tried using another tutorial, it builds successfully but crashes as soon as I attempt to call the method.
public static String URLConnection() throws IOException, JSONException {
URL url = new URL("https://api./api/graphql/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.addRequestProperty("curl", "'https:/api/graphql/'");
connection.addRequestProperty("content-type", "application/json");
connection.addRequestProperty("accept", "application/json");
connection.addRequestProperty("x-api-key", "'xxxxxxxxxxx'");
connection.addRequestProperty("--data-binary", "{\"query\":\"{Search(query:\"Query\"){items{description}}}\",\"variables\":\"{}\",\"operationName\":null}");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
JSONObject jsonParam = new JSONObject();
jsonParam.getString("description");
OutputStream os = connection.getOutputStream();
os.write(Integer.parseInt(URLEncoder.encode(jsonParam.toString(), "UTF-8")));
os.close();
try {
InputStream in = connection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next();
} else {
return null;
}
} finally {
connection.disconnect();
}
}
I'm a bit stuck here and I don't know why. It's probably very simple. I want to post changes to a Wordpress site from a Java app.
The following curl example does as it should:
curl -X POST -H "Content-Type: application/json" -d '{"title":"hello123"}' -u user:pass http://myurl.com/wp-json/wp/v2/posts/219 -v
The following code example not:
try {
URL url = new URL("http://myurl.com/wp-json/wp/v2/posts/219");
String encoding = Base64.encodeBase64String((txtUserName.getText() + ":" + txtPassword.getText()).getBytes());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Authorization", "Basic " + encoding);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("POST");
connection.connect();
ObjectMapper post = new ObjectMapper();
ObjectNode node = post.createObjectNode();
node.put("title", "test1234");
OutputStream os = connection.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(os, "UTF-8");
outputStreamWriter.write(post.toString());
outputStreamWriter.flush();
outputStreamWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
So I'm grateful for any help.
Thank you very much
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