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
Related
I'm trying to set up stripe connect (https://stripe.com/docs/connect/standalone-accounts) on my application, but I'm failing to set up the link between the platform and the standalone account. It provides a curl code to execute, and examples in ruby, python, PHP and node; but no java.
The curl call is as follows:
curl https://connect.stripe.com/oauth/token \ -d client_secret=sk_test_IgHHUgcqKmxA8Yyai9ocqpZR \ -d code=AUTHORIZATION_CODE \ -d grant_type=authorization_code
It looks pretty simple, but I have no idea how this works. I have been looking around trying to figure out how to make this call in java, and so far I haven't been able to.
Finally i got the correct code to run the curl command ,but it gives bunch of result.but i want only paricular id in it.how can i get that?
`URL url = new URL("https://connect.stripe.com/oauth/token");
Map<String,Object> params = new LinkedHashMap<>();
params.put("client_secret",API_KEY);
params.put("code", code);
params.put("grant_type", "authorization_code");
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
for (int c; (c = in.read()) >= 0;)
sb.append((char)c);
String response = sb.toString();`
and i got
response={
"access_token": "xxxxxxxxxxxxxxxxx",
"livemode": false,
"refresh_token": "xxxxxxxxxxxxxxxxxxxxxxxt",
"token_type": "bearer",
"stripe_publishable_key": "xxxxxxxxxxxxxxxxxxxxxxxx",
"stripe_user_id": "xxxxxxxxxxxxxxxxxxxxxxxxx",
"scope": "express"
}
how can i get only the stripe_user_id in java
The -d parameters in curl are for POST data (see the curl man page). POST is the method for sending form data (e.g. when you submit a web form). Rather than putting the parameters on the end of the URL, like you would in a GET request, the parameters are encoded and sent inside the "body" of the request.
Take a look at this answer or this one for various ways you can send POST data with requests from Java.
Alternatively, you could execute the curl process from Java. See this example.
There are various ways to establish connections to outbound servers. Here is an example of a Stripe OAuth integration, using Apache HttpComponents.
I got an answer for that one using JSONObject,
JSONObject jObject = new JSONObject(response);
String stripe_user_id=(String) jObject.get("stripe_user_id");
I want to call this curl command to get list of applicant names from Java in JSON
curl -u uname:pass my_REST_Endpoint_provided_by_vendor
here is my code:
URL myURL = new URL("url");
HttpURLConnection conn = (HttpURLConnection) myURL.openConnection();
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setRequestMethod("PUT");
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(unamepass.getBytes("UTF-8"));
conn.setRequestProperty ("Authorization", basicAuth);
int code = conn.getResponseCode(); // 200 = HTTP_OK
System.out.println("Response (Code):" + code);
System.out.println("Response (Message):" + conn.getResponseMessage());
If I run this command on my command prompt it runs fine and gives me the output but if I run this code I get Response (Code):405
java.io.IOException: Server returned HTTP response code: 405 for URL:
Where am I going wrong?
You are getting an 405 error because you are using the HTTP Method PUT instead of GET, which is used by curl by default. Remove the line:
conn.setRequestMethod("PUT");
I am trying to send json data to Influx db using following code:
String url = "http://xx.x.xx.xx:8086/db/monitoring/check_1113?u=root&p=root";
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setRequestMethod("PUT");
//String userpass = "user" + ":" + "pass";
//String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes("UTF-8"));
//conn.setRequestProperty ("Authorization", basicAuth);
//String data = "{\"format\":\"json\",\"pattern\":\"#\"}";
System.out.println("Data to send: "+"[{\"name\": \"check_222\",\"columns\": [\"time\", \"sequence_number\", \"value\"],\"points\": [["+unixTime+", 1, \"122\"]]}]");
String data = "[{\"name\": \"check_333\",\"columns\": [\"time\", \"sequence_number\", \"value\"],\"points\": [["+14444444444+", 1, \"122\"]]}]";
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write(data);
out.close();
new InputStreamReader(conn.getInputStream());
System.out.println("Data Sent");
Where xx.xx.xx.xx is the ip of server where influx is deployed and i am using the Ip.
When i do a manual curl with this data (on localhost), the data is sent successfully. curl is provided below:
curl -X POST -d '[{"name": "check_223","columns": ["time", "sequence_number", "value"],"points": [[1445271004000,1,70.8880519867]]}]' 'http://localhost:8086/db/monitoring/series?u=root&p=root'
But when I run the code to send the data via the java program shared above, i get following error:
java.io.FileNotFoundException: http://xx.x.xx.xx:8086/db/monitoring/check_1113?u=root&p=root
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1834)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1439)
at com.snapdeal.hadoop.monitoring.hdfs1.App.sendJsonDataToInflux(App.java:52)
at com.snapdeal.hadoop.monitoring.hdfs1.App.main(App.java:89)
[INFO - 2015-10-20T16:27:13.152Z] ShutdownReqHand - _handle - About to shutdown
And to add to it, I am using phantomJS to get the data from web page and pass that data in the JSON request. But for simplicity I have hard-coded it at present.
This should be relatively obvious. A 405 indicates that the HTTP Method on the request is not supported by the endpoint. The service you are calling does not support a PUT method.
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!
I have something that looks like this:
POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded
grant_type=assertion&assertion_type=http%3A%2F%2Foauth.net%2Fgrant_type%2Fjwt%2F1.0%2Fbearer&assertion=eyJhbGciOiJSUzI1NiIs
How would I go about using this in Java? I have all the information already so I wouldn't need to parse it.
Basically I need to POST with 3 different data and using curl has been working for me but I need to do it in java:
curl -d 'grant_type=assertion&assertion_type=http%3A%2F%2Foauth.net%2Fgrant_type%2Fjwt%2F1.0%2Fbearer&assertion=eyJhbGciOiJSUzI1NiIsInR5i' https://accounts.google.com/o/oauth2/token
I cut off some data so its easier to read so it wont work.
So a big problem is that the curl would work while most tutorials I try for Java would give me HTTP response error 400.
Like should I be encoding the date like this:
String urlParameters = URLEncoder.encode("grant_type", "UTF-8") + "="+ URLEncoder.encode("assertion", "UTF-8") + "&" + URLEncoder.encode("assertion_type", "UTF-8") + "=" + URLEncoder.encode("http://oauth.net/grant_type/jwt/1.0/bearer", "UTF-8") + "&" + URLEncoder.encode("assertion", "UTF-8") + "=" + URLEncoder.encode(encodedMessage, "UTF-8");
or not:
String urlParameters ="grant_type=assertion&assertion_type=http://oauth.net/grant_type/jwt/1.0/bearer&assertion=" + encodedMessage;
Using this as the code:
URL url = new URL(targetURL);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
Use something like HttpClient or similar.
It can post pre-URL-encoded data to a URI, although I don't know if you could just throw a complete request body at it--might need to parse it out, but there are likely libraries for that as well.
Here's a simple example of Apache HttpClient with request body from their docs (slightly modified to show how the execute works):
HttpClient client = new HttpClient();
PostMethod post = new PostMethod("http://jakarata.apache.org/");
NameValuePair[] data = {
new NameValuePair("user", "joe"),
new NameValuePair("password", "bloggs")
};
post.setRequestBody(data);
int returnCode = client.execute(post);
// check return code ...
InputStream in = post.getResponseBodyAsStream();
See the Apache HttpClient site for more info, examples and tutorials. This link might help you too.