Trying to use HttpURLConnection to send HTTP chunked POST request.
conn.setRequestMethod("POST");
conn.setChunkedStreamingMode(16000);
conn.setRequestProperty("format", "InterleavedInt16");
conn.setRequestProperty("number-of-channels", "2");
conn.setRequestProperty("format", "InterleavedInt16");
conn.setRequestProperty("transfer-encoding", "chunked");
conn.setReadTimeout(12000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
have setup the conn as above. My question is do I need to manually breakdown the outputstream as to the chunk size. and call out.write() multiple times for each chunk. Or I can just call out.write() once but pass in the whole stream?
My current code to send the whole stream(assume size is 32000):
byte[] data = new byte[32000];
inputStream.read(data);
OutputStream out = conn.getOutputStream();
conn.connect();
out.write(data);
audioStream.close();
out.close();
This give me a "unexpected end of stream on Connection" error.
Related
I want to post the request in same formate.
POST /mga/sps/oauth/oauth20/token HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
Authorization: Basic aaabbbCCCdddeeefffGGG
client_id=xxx&client_secret=yyy&grant_type=authorization_code
&code=3v6MJzt9vKtRkxpTFnkJG3IyspWC2k
&redirect_uri=xyz%2Ffolder
I have Implemented but getting bad request and unable to print the post content what I am sending I also want to get the json response after sending this request.
String urlParameters = "grant_type=authorization_code"+"&redirect_uri="+session.getAttribute("redirect_uri")+"&code_verifier="+session.getAttribute("codeVerifier")+"&code="+session.getAttribute("code")+"&state="+session.getAttribute("state");
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
URL url = new URL( "https://example/oauth20/token" );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length",
Integer.toString(postDataLength ));
conn.setRequestProperty("Host","example.com");
conn.setRequestProperty("Authorization","clientID=xyz");
conn.setUseCaches(false);
DataOutputStream wr = new
DataOutputStream(conn.getOutputStream());
wr.write(postData);
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());
conn.disconnect();
You have multiple options.
You can start with Java HTTP Client - Refer
The HTTP Client was added in Java 11. It can be used to request HTTP
resources over the network. It supports HTTP/1.1 and HTTP/2, both
synchronous and asynchronous programming models, handles request and
response bodies as reactive-streams, and follows the familiar builder
pattern.
Apache HttpClient - Refer
RestTemplate - Refer
JAX-RS Client - Example
Spring 5 WebClient - Example
OkHttpClient - Example
Comparison
I am trying to do a http PATCH request but I always get the 404 error, so maybe the settings of my connection are not correct:
URL url = new URL("MyPath");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("X-HTTP-Method-Override", "PATCH");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestMethod("POST");
JsonObject jo = createMyJson();
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write(jo.toString());
out.close();
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());
I get the 404 error, Not found. When doing the same request using Postman, this is working..
Thank you for your help.
Not all servers support X-HTTP-Method-Override. In that case your last resort is (if you are not using a decent HTTP client) to hack the URLConnection object.
I posted a complete solution here on SO, check it out.
We have this code which we are using to post data from an Android app to a .Net Rest service. One of the fields that the backend is and array. Swagger specifies it as
modelbinding Array[integer]
How should we put the value array of integers in the urlParameters so we can post it?
String urlParameters = "field1=abc&field2=def";
URL url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
// Send request
writer = new DataOutputStream (connection.getOutputStream ());
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(writer, "UTF-8"));
bufferedWriter.write(urlParameters);
bufferedWriter.flush ();
bufferedWriter.close ();
Using Json format is the best way to send data. you can convert your data in json array then json array to string. Now your string(represented in json formate) can easily be sent.
We are sending HTTPURLRequest to server.
When we are sending English content its working fine.But, when we are sending Arabic language content we are getting
Server returned HTTP response code: 500
We had written below code
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(SendRequest.getBytes().length));
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
dataout.writeBytes(SendRequest);
dataout.flush();
dataout.close();
BufferedReader bufferreader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
When I use connection.getInputStream() I am getting 500 error
We are using utf-8 also.But, still getting the error
can any one help me
You can use a library to escape the special chars:
StringEscapeUtils.escapeJava("هولاء كومو")
This class is available on: Commons Lang from Apache
Hope this helps!
Check the HTTP Status Response Codes. An error happened on the server, so the diagnostics will need to be performed on the server, not on the client.
I've got a legacy application that writes to an OutputStream, and I'd like to have the contents of this stream uploaded as a file to a Servlet. I've tested the Servlet, which uses commons-fileupload, using JMeter and it works just fine.
I would use Apache HttpClient, but it requires a File rather than just an output stream. I can't write a file locally; if there was some in-memory implementation of File perhaps that might work?
I've tried using HttpURLConnection (below) but the server responds with "MalformedStreamException: Stream ended unexpectedly".
URL url = new URL("http", "localhost", 8080, "/upload");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
String boundary = "---------------------------7d226f700d0";
connection.setRequestProperty("Content-Disposition", "form-data; name=\"file\"");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestMethod("POST");
connection.setChunkedStreamingMode(0);
connection.connect();
OutputStream out = connection.getOutputStream();
byte[] boundaryBytes =("--" + boundary + "\r\n").getBytes();
out.write(boundaryBytes);
//App writes to outputstream here
out.write("\r\n".getBytes());
out.write(("--"+boundary+"--").getBytes());
out.write("\r\n".getBytes());
out.flush();
out.close();
connection.disconnect();
The PostMethod allows you to set a RequestEntity, which is an interface which you can implement. you just need to implement the RequestEntity.writeRequest method appropriately.
Or, if you want HttpClient to handle the multi-part stuff for you, you could use MultipartRequestEntity with a custom Part.