send file as a data binary to http post spring boot - java

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.

Related

Java HTTP POST request code equivalent to curl call

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

Pass json object by navigator instead of java

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.

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

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?

Post Request clone on Android

Im trying to perform the folowing request in my android app.
The Request i send was on a Chrome Browser.
In the Request i shortend the Form Data so there is not so much code.
Request URL:http://***/
Request Method:POST
Status Code:200 OK
Request Headers
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding:gzip,deflate,sdch
Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
Cache-Control:max-age=0
Connection:keep-alive
Content-Length:424
Content-Type:application/x-www-form-urlencoded
Cookie:__utma=188893489.1646114392.1358703936.1367178892.1368783485.29; __utmz=188893489.1365594840.21.3.utmcsr=***|utmccn=(referral)|utmcmd=referral|utmcct=/
Host:***
Origin:***
Referer:**
User-Agent:Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36
Form Data
date=1375480155&mail=&dfBoot=Test
Response Headers
Connection:Keep-Alive
Content-Encoding:gzip
Content-Length:3614
Content-Type:text/html
Date:Fri, 02 Aug 2013 21:49:59 GMT
Keep-Alive:timeout=15, max=100
Server:Apache/2.2.14 (Ubuntu)
Vary:Accept-Encoding
X-Powered-By:PHP/5.3.2-1ubuntu4.20
with this code:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
URL url = new URL("http://***/index.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length",String.valueOf(post.length()));
//connection.setChunkedStreamingMode(0);//results in frezing
OutputStreamWriter writer = new OutputStreamWriter(
connection.getOutputStream());
writer.write(post);
writer.flush();
InputStream in = new BufferedInputStream(
connection.getInputStream());
while (in.available() != 0) {
in.read();
}
writer.close();
in.close();
} finally {
connection.disconnect();
}
The code is very messed up because i tryed manytime to fix my connection problem.
Please help with a better Solution.
Hm, I will show my working code with JSON, but maybe you can modify it.
URL url = new URL("http://xcxcxcxcxcx");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(jsonObject.toString().getBytes().length));
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.connect();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(jsonObject.toString());
out.flush();
out.close();
InputStream is = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(is);
BufferedReader r = new BufferedReader(reader);
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
JSONObject jsonObjectResult = null;
if(typeOfMethod == 0){
JSONTokener tokenizer = new JSONTokener(total.toString());
jsonObjectResult = new JSONObject(tokenizer);
}
connection.disconnect();
return jsonObjectResult;
There is some differences between getting result from InputStream.

Categories