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
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'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 have cURL
curl -i https://thisIsValidUrl \
-X PUT \
-H "Content-Type: application/json" \
-u YOUR-SITE-ID-HERE:YOUR-SECRET-API-KEY-HERE \
-d '{"email":"customer#example.com","created_at":1361205308,"first_name":"Bob","plan":"basic"}'
i need to post a request using spring restTemplate, but i cannot find how to use the -u
found it , it is just means to use basic authentication, i should encrypt YOUR-SITE-ID-HERE:YOUR-SECRET-API-KEY-HERE as Base64 String and use it in Authorization header
MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
RestTemplate restTemplate = new RestTemplate();
headers.add("Authorization", "Basic " + Base64String);
headers.add("Content-Type", "application/json");
.
.
.
HttpEntity<RaisEventRequest> request = new HttpEntity<RaisEventRequest>(RaisEventRequest, headers);
ResponseEntity<RaisEventResponse> responseEntity = restTemplate
.exchange(eventsURL, HttpMethod.POST, request, RaisEventResponse.class);
return responseEntity.getBody();
I have a line of code that I'm using in a shell script to send notifications to some users. I need to be able to use it in a Java application as well, but I am stuck on how to convert it to something Java would understand.
This is what the shell command looks like:
curl -u key:secret -d email=user#example.com \
--data-urlencode msg="test message" \
--data-urlencode url="http://www.airgramapp.com/welcome" \
https://api.airgramapp.com/1/send -k
Here's what I have so far:
URL url = new URL("curl -u key:secret -d email=user#example.com \
--data-urlencode msg="test message" \
--data-urlencode url="http://www.airgramapp.com/welcome" \
https://api.airgramapp.com/1/send -k");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"))) {
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
}
}
Any help or guidance in the right direction would be greatly appreciated!
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!