I'm trying to get data from a API's endpoint and I have noticed the data I'm trying to get by HTTP POST method is huge and the API's server respond me with a response with one of headers set as Transfer-Encoding: chunked and I'd like to read the whole data. In my code I'm using the java.net.HttpURLConnection to establish my post request and read the data as showed bellow.
Unfortunately for this scenario I'm getting java.io.IOException: Premature EOF at the line where I read from the BufferedReader(while((output = br.readLine()) != null)) I debugged it and I'm getting status http 200 until right before the Exception has been threw.
Is there anything wrong in requesting chunked data like showed in my code?
Thank you.
String responseStr = "";
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) new URL(this.url).openConnection();
connection.setRequestProperty("content-type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
os.write(payloadToBeRequested.getBytes());
os.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String output = "";
while((output = br.readLine()) != null){
responseStr = responseStr + output;
}
status = connection.getResponseCode();
connection.disconnect();
}catch(MalformedURLException ex){
ex.printStackTrace();
}catch(IOException ex){
ex.printStackTrace();
}
Related
I have a node.js which waits for post with 2 parameters (name and pass):
app.post('/login.html', function (req, res) {
log.info(req.body);
userName = req.body.name;
pass = req.body.pass;
...
}
I'm trying to send post with the 2 parameters via simple java application, but I can't see that it arrive to the node.js.
what am I missing ?
The java code:
public static void main(String[] args) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://83.63.118.111:31011/login.html");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlConnection.setConnectTimeout(10000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
String str = "name='root'&pass='123456'";
//System.out.print(str);
writer.write(str);
writer.flush();
Thread.sleep(100);
writer.close();
os.close();
}
Your code will close when start send data (send and stop)
You should wait it done.
Add code after writer.flush();
Example get response:
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
or just get responseCode:
int responseCode = urlConnection.getResponseCode();
Your program wait send request success or fail.
I think you use Thread.sleep(100); to wait send request, but it stop your Thread (don't send data to server)
Your code have req.body, Express.js don't have it, need use middleware body-parser.
I am opening an HttpURLConnection and with POST method, I am sending a JSON request that I build form another class. The JSON is structured correctly since I have validated it on debugging. The exception is thrown when trying to read the output response given from the server. This is the Error given
java.io.IOException: Server returned HTTP response code: 400 for URL:
However when I manually try to enter the Url from a web browser with a POST method chrome extension. I can view the response and everything works. So I am sure it has something to do with the following code where I make the connection and read/write.
URL obj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
//add request header
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
//mapping objects to json
BatchRequest requestParameters = new BatchRequest(o,d);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(requestParameters);
connection.setDoOutput(true);
DataOutputStream os = new DataOutputStream(connection.getOutputStream());
os.writeBytes(json);
os.flush();
os.close();
// this is where the program throws the exception
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Both the URL and the JSON request are correct since They work when I try a manual conenction over a browser.
A DataOutputStream is not needed. Just:
OutputStream os = con.getOutputStream();
I am using Java.Net.URL for making a Rest webservice call.
using the below example code.
URL url = new URL("UrlToConnect");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input = "{\"qty\":100,\"name\":\"iPad 4\"}";
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());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
i am trying to capture response code from this webservice call. I observed that Even after putting a wrong URL i am getting 200 response code from the connection. Please suggest a way by which i can capture response codes 200 , 201 and 202.
Thanks.
I am trying to send the a JSON to server but it constantly returns 500 error.
java.lang.String contentToPost = jsarray.toJSONString();
java.net.URLConnection connection = new java.net.URL("http://example.com/service?apiKey=12345").openConnection();
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Length", "" + contentToPost.length());
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Cache-Control", "no-cache");
java.io.OutputStream stream = connection.getOutputStream();
stream.write(contentToPost.getBytes());
stream.close();
System.err.println("request is sent");
// Read the response
java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(connection.getInputStream()));
java.lang.StringBuffer sb = new java.lang.StringBuffer();
java.lang.String str = br.readLine();
while (str != null) {
sb.append(str);
str = br.readLine();
}
br.close();
java.lang.String responseString = sb.toString();
System.err.println(responseString);
Error
java.io.IOException: Server returned HTTP response code: 500 for URL: http://example.com/service?apiKey=12345
Because the server or server application had an internal error handling your request.
This error can only be resolved by fixes to the Web server software. It is not a client-side problem. It is up to the operators of the Web server site to locate and analyse the logs which should give further information about the error.
I am sending json string in an https post request to an apache servert(request sends json data to a cgi-bin script that actually is a python script). Am using a standard cgi call -
f=open("./testfile", "w+")
f.write("usageData json = \n")
<b>form = cgi.FieldStorage()
formList = ['Data']
str = form['Data'].value
str = json.dumps(backupstr)
</b>
print backupstr
to read the json string in the url. Problem is that the script is not reading the json in the url even though the script is getting fired (the basic print statements are executing ...). This is how am sending data from the post side :
HttpsURLConnection connection = null;
try{
connection = (HttpsURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/json");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(jsonstring.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
//wr.writeBytes(jsonstring);
wr.writeUTF(URLEncoder.encode(jsonstring, "UTF-8"));
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);
}
rd.close();
//response = httpClient.execute(request);
}
catch (Exception e)
{
System.out.println("Exception " + e.getMessage());
throw e;
}
I suspect am missing one or more of the connection.setRequestProperty() settings on the sending end that's why it's firing the script but not reading the json string in the url ...what am I doing wrong ...?