I have a server running tomcat 7, and I've noticed that whenever a client performs multiple serial requests to the server (around 10), it stops responding and causes a timeout on the client.
Seeing the server's logs, I've noticed that the server does's even receive the request.
Here is the client implementation:
try{
String http = "...";
int i;
for(i=0;i<1000;i++){
http += "?id="+ String.valueOf(i);
URL url = new URL(http);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
conn.setDoInput(true);
conn.connect();
BufferedReader inc = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = inc.readLine()) != null){
System.out.println(inputLine);
}
inc.close();
conn.disconnect();
}
br.close();
}catch(Exception e){
e.printStackTrace();
}
Related
As the title, I want to implement a Web server by Java, the only problem is that I need post a form to login.php and then get the response.
The following code is how I post the data to PHP.
URL url = new URL("http://127.0.0.1:6789" + req.uri);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Convert string to byte array, as it should be sent
// req.form is the form data to post to the login.php
byte[] postDataBytes = req.form.getBytes(StandardCharsets.UTF_8);
// set the form from request as the post data to PHP
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.getOutputStream().write(postDataBytes);
// get response
int code = conn.getResponseCode();
InputStream is;
if (code == 200) {
is = conn.getInputStream();
fillHeaders(Status._200_);
} else {
is = conn.getErrorStream();
fillHeaders(Status._404_);
}
// get response conetent length from login.php
int length = conn.getContentLength();
The content of login.php is very simple:
<?php
echo 'User name is:' . $_POST['loginName'];
?>
When I debug this part, I will stall in this line
int code = conn.getResponseCode();
That means I cannot get response from login.php
So how can I change the code or the enviornment of ubuntu (maybe the version of php?) to solve this problem.
Thx. XD
If java is the server and PHP is a client you should open listening connection in java.
ServerSocket server = new ServerSocket(8080);
System.out.println("Listening for connection on port 8080 ....");
while (true) {
Socket clientSocket = server.accept();
InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
BufferedReader reader = new BufferedReader(isr);
String line = reader.readLine();
while (!line.isEmpty()) {
System.out.println(line); line = reader.readLine();
}
}
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();
}
I am working on a Java desktop application with Java 7. For my application, I want to send data with POST to a server (using HTTP). The server is running on my local machine on localhost.
But if I am trying to connect to the server, an connection reset (SocketTimeoutException) is returned. I can`t connect, I have also tried to connect to a webpage like http://www.google.de, but it also fails. The var body contains the POST data in correct form. (I have also tried to connect with disabled firewall)
My code:
body=body.substring(0,body.length()-2);
HttpURLConnection connection = null;
try {
if (revision){ //Connect to the revision server
this.urlRevision = new URL(this.settingsRevision.getAddress());
connection = (HttpURLConnection) urlRevision.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", String.valueOf(body.length()));
connection.connect();
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(body);
writer.flush();
this.returnedData = new BufferedReader(new InputStreamReader(connection.getInputStream()));
for(String line; (line = returnedData.readLine()) != null;){
System.out.println(line);
}
writer.close();
this.returnedData.close();
}
} catch (Exception e) {
this.exception=e;
}
You should try close the connection like this:
} finally {
if(connection != null) {
connection.disconnect();
}
}
I have already added it to the comments:
System.setProperty("java.net.preferIPv4Stack" , "true");
Reason: Java is using IPv6 functions on my computer but IPv4 is used for internet connection (on my computer and by my provider (T-Online)).
I am trying to send an HTTP POST Request to a remote server using an instance of the HttpURLConnection class. Although, I am able to get a response code and a response message, when I try to write the input stream into a StringBuffer, I am not able to actually read any lines.
When I analyzed the packets sent from WireShark, I noticed that a full response was being sent from the remote server. My only guess as to why I am not able to see it in the Java program is because the time in which I try to read from the InputStream is too late.
So, how do I read the immediate, full response from the remote server using my HttpURLConnection object? Below is the code that I am using:
HttpURLConnection conn = null;
String urlStr = "...";
URL url = null;
try
{
url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
...
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null)
{
sb.append(line);
}
rd.close();
...
}...
Okay, never mind. It turns out that what I was looking for was in the HTTP Respone's header. So, I got what I needed by looking through its headers. ::Face Palm::
I´m trying to send a post request with cookies. This is the code:
try {
String query = URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode("value", "UTF-8");
String cookies = "session_cookie=value";
URL url = new URL("https://myweb");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestProperty("Cookie", cookies);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(query);
out.flush();
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
// Send the request to the server
//conn.connect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The problem is the request is sent without the cookies. If I only make:
conn.connect(); and don´t send data, the cookies are sent OK.
I can´t check exactly what is happening, because the connection is thorugh SSL. I only check the response.
According to the URLConnection javadoc:
The following methods are used to access the header fields and the
contents AFTER the connection is made to the remote object:
* getContent
* getHeaderField
* getInputStream
* getOutputStream
Have you confirmed that in your test case above the request is getting to the server at all? I see you have the call to connect() after getOutputStream() and commented-out besides. What happens if you uncomment it and move up before the call to getOutputStream() ?