Java HTTP POST request code equivalent to curl call - java

curl -X POST --header "Content-Type: text/plain" --header "Accept: application/json" -d "HELLO THERE" "http://localhost:8080/rest/items/Echo_Living_Room_TTS"
I want to write Java code that does the same thing as this curl invocation. Here's what I've written so far:
URL myurl =new URL("http://localhost:8080/rest/items/Echo_Living_Room_TTS");
HttpURLConnection connection = (HttpURLConnection) myurl.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","text/plain");
connection.connect();
String urlParameters = "HELLO THERE";
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
if(something happens) {
try( DataOutputStream wr = new DataOutputStream( connection.getOutputStream())) {
wr.write( postData );
}
}
connection.disconnect();
Have I done it right? Are there any mistakes or omissions?

Ok seems like I made it works:
URL myurl =new URL("http://localhost:8080/rest/items/Echo_Living_Room_TTS");
HttpURLConnection connection = (HttpURLConnection) myurl.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","text/plain");
connection.setRequestProperty("Accept","application/json");
String mystring = "whatever";
byte[] postData = mystring.getBytes( StandardCharsets.UTF_8 );
int lenght = postData.length;
connection.setFixedLengthStreamingMode(lenght);
connection.connect();
try(OutputStream os = connection.getOutputStream()) {
os.write( postData );
}
connection.disconnect();
thank you all

Related

send file as a data binary to http post spring boot

I have a curl command:
curl -X POST "https:example.com/upload" -H "accept: application/json" -H "Authorization: token" -H
"Content-Type: text/plain" --data-binary #"filename.txt"
this is the code so far:
SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
URL url = new URL("https://example.com/upload");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setSSLSocketFactory(sslsocketfactory);
conn.setRequestMethod("POST");
conn.setRequestProperty("accept", "application/json");
conn.setRequestProperty("Authorization", encodedValue);
conn.setRequestProperty("Content-Type", "text/plain");
OutputStream os = new BufferedOutputStream(conn.getOutputStream());
byte[] bytes = Files.readAllBytes(Paths.get(filePath));
os.write(bytes);
os.flush();
int respCode = conn.getResponseCode();
System.out.println(respCode);
if (conn.getResponseCode() != 404) {
InputStream inputstream = conn.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
while ((client = bufferedreader.readLine()) != null) {
response.getWriter().println(client);
}
}
I am getting a 404 response.
can someone help me what am I doing wrong here? Please and thanks.

Post JSON Data from Java to Wordpress WP API v2

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

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();

Send post data from android

I'm sending a POST request to certain server.
I can send the date from curl like this:
curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST https://ictexpo.herokuapp.com/users -d "{\"user\":{\"name\":\"Choity\"}}"
But when I want to send the same data from java I don't get the outcome.
String urlParameters = "{\"user\" : {\"name\" : \"lssl\" }}";
URL url2 = new URL(url);
HttpsURLConnection connection = (HttpsURLConnection) url2.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept","application/json");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
//Send request
DataOutputStream wr = new DataOutputStream (connection.getOutputStream());
wr.writeBytes (urlParameters);
wr.flush();
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
Can anyone please tell me why I'm getting exceptopn?

Won't send all parameters to post http request

I am trying to send a http request with java. This is my code:
String AnnonseUrl = "http://webpage.no/insert_annonse.php?info="+info+"&tittel="+tittel+"&bedriftsNavn="+bedriftsNavn+"&kontaktEmail="+kontaktEmail+"&varighet="+varighet+"&frist="+frist+"&url="+url+"&sted="+sted+"&kontaktNavn="+kontaktNavn;
URL url = new URL(AnnonseUrl);
URLConnection uc = url.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
uc.getInputStream()));
in.close();
Only the first three parameters are submitted..
If I copie the string "AnnonseUrl" and paste it in to my browser, then everything works fine.
When doing a post the parameters are send in the Http Body:
Try this:
URL u = new URL("http://www.stackoverflow.com");
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setDoOutput(true);
conn.connect();
DataOutputStream wr = new DataOutputStream (
conn.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush();
wr.close();
Where urlParameters is something like:
String urlParameters =
"tittel="+URLEncoder.encode(tittel,"UTF-8")
+"&bedriftsNavn"+URLEncoder.encode(bedriftsNavn,"UTF-8");

Categories