I get EOFException while trying to get response from the server - java

I use a PrintWriter out object. I write data out.println(some data) and close it with a out.close
URL url = new URL(myurl);
URLConnection connection = null;
PrintWriter out = null; BufferedReader br = null; connection = url.openConnection(); connection.setDoOutput(true);
out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream()),true);
while(iterations) {
//print data on writer
out.println(object);
}
//closig print writer
out.flush();
out.close();
//Response from server
br = new BufferedReader(new InputStreamReader(connection.getInputStream())); // Get Exception in //this line EOF Exception
String temp;
while(temp = br.readLine() !=null) {
//do something
}
br.close();

URL url = new URL(myurl);
URLConnection connection = null;
PrintWriter out = null; BufferedReader br = null; connection = url.openConnection(); connection.setDoOutput(true);
out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream()),true);
while(iterations)
{
//print data on writer
out.println(object);
}
//closig print writer
out.flush();
//Response from server
br = new BufferedReader(new InputStreamReader(connection.getInputStream())); // Get Exception in //this line EOF Exception
String temp;
while(temp = br.readLine() !=null)
{ //do something }
out.close();
Have a look at the code, you just had to put out.close instead of br.close at the end.

Related

Json came null in Android Java

Error:
E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of
I have to send image to server with post method but I cant send. Json came to me null. There is my code:
if (method.equalsIgnoreCase("POST")) {
URL url_ = new URL(url);
String paramString = URLEncodedUtils.format(params, "utf-8"); // unused
HttpURLConnection httpConnection = (HttpURLConnection) url_.openConnection();
httpConnection.setReadTimeout(10000);
httpConnection.setConnectTimeout(15000);
httpConnection.setRequestMethod("POST");
httpConnection.setDoInput(true);
httpConnection.setDoOutput(true);
InputStream in = httpConnection.getInputStream();
OutputStream out = new FileOutputStream(picturePath);
copy(in, out);
out.flush();
out.close();
httpConnection.connect();
//Read 2
BufferedReader br = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
String line2 = null;
StringBuilder sb = new StringBuilder();
while ((line2 = br.readLine()) != null) {
sb.append(line2);
}
br.close();
json = sb.toString();
}
How can I send image to server?
Thanks..

java.lang.IllegalStateException: Cannot use BufferedReader while ServletInputStream is in use

Can Java experts help me on this issue, I'm geting the error below
java.lang.IllegalStateException: Cannot use BufferedReader while ServletInputStream is in use
I'm calling a REST service url to post some data using a server side java code, not through a browser.
try{
String urlLocation = "http://myserver/james/dev/hello.nsf/services.xsp/test";
URL url = new URL(urlLocation);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setAllowUserInteraction(false);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestProperty( "Content-type", "application/x-www-form-urlencoded" );
//connection.setRequestProperty( "Content-length", Integer.toString(content.length()));
DataOutputStream out = new DataOutputStream (connection.getOutputStream ());
out.writeBytes (getXML());
out.flush ();
out.close ();
connection.disconnect();
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while( (line = in.readLine()) !=null) {
System.out.println(line);
}
in.close();
}
catch(Exception e){
System.out.println("Error from 2nd try statement");
e.printStackTrace();
e.toString();
}
Any help will be greatly appreciated...
It seems to be this line
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
I noticed the BufferedReader is not being instantiated, you are reusing an instance variable in.
I copied your code and just changed it to this, and I can make multiple requests without any problem.
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));

Encoding trouble: php api and java client program

I am sorry to post such a "noob question", but I can't solve my problem by myself.
I have a server-side script, written in php which returns different values, in this example all companynames which are stored in a MySQL DB.
-The column in the DB is encoded in UTF-8
-The php file is encoded in UTF-8
This is the server side script:
include_once('SQLHandler.php');
$SQLHandler = new SQLHandler();
if(isset($_POST['command'])){
$command = $_POST['command'];
switch($command){
case 'getCompanies':
echo utf8_encode('[["Test1"],["Test2"],["Test3"],["Test4"]]');
//echo json_encode( $SQLHandler -> getCompanies());
break;
}
}
it returns "[["Test1"],["Test2"],["Test3"],["Test4"]]".
However, when I want to analyze the returned String and parse it to an array (with json-simple library), the following occurs:
?[["Test1"],["Test2"],["Test3"],["Test4"]]
Unexpected token END OF FILE at position 0.
The Java Code is the following:
ArrayList companies = new ArrayList<>();
try {
URL url = new URL("http://localhost/api.php");
URLConnection conn = url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
String content = "command=getCompanies";
out.writeBytes(content);
out.flush();
out.close();
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String line;
while ((line = rd.readLine()) != null){
System.out.println(line);
}
String jsonText = readAll(rd);
is.close();
JSONArray array = (JSONArray) new JSONParser().parse(jsonText);
System.out.println(array);
System.out.println(array.toJSONString());
System.out.println(array.toString());
} catch(Exception e){
e.printStackTrace();
}
return null;
It is my first time working with java and json, so it is possible that I did a very easy to find error, but I would be very thankfull if you could point it out to me (and explain what I did wrong;))
Regards
Well, turns out it wasn't an encoding problem at all...
See my modified code:
ArrayList companies = new ArrayList<>();
try {
URL url = new URL("http://localhost/api.php");
URLConnection conn = url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
String content = "command=getCompanies";
out.writeBytes(content);
out.flush();
out.close();
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String wholeLine = "";
String line;
while ((line = rd.readLine()) != null) {
wholeLine = wholeLine + line;
}
is.close();
JSONArray array = (JSONArray) new JSONParser().parse(wholeLine);
for(Object obj : array.toArray()){
System.out.println(obj.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
I forgot to supply "line" to the parse function and instead parsed the wrong variable ^^
Regards

bufferedreader Inputstream reader changes...?

URL u = new URL(url);
String expected = "";
HttpURLConnection uc = (HttpURLConnection) u.openConnection();
InputStream in = new BufferedInputStream(uc.getInputStream());
Reader r= new InputStreamReader(in);
so here is my code and i want a very little help that is the above is to fetch the content from url but now i want to use the same code for reading content from file what i need to change in above code....i mean there should be something which i need to change in the place of uc.getInputStream()...so what is that
InputStream in = new BufferedInputStream(uc.getInputStream());
Look at class FileInputStream.
You can simply user that code and do it in similar way.
InputStream in = new FileInputStream(new File("C:/temp/test.txt"));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
System.out.println(out.toString()); //Prints the string content read from input stream
reader.close();

tcp/ip open connection

currently i am using the following code to interact with server
public String connectToserverforincomingmsgs(String phonurl, String phno)
throws IOException {
URL url = new URL(phonurl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoInput(true);
// Allow Outputs
con.setDoOutput(true);
con.connect();
BufferedWriter writer = null;
writer = new BufferedWriter(new OutputStreamWriter(
con.getOutputStream(), "UTF-8"));
// give server your all parameters and values (replace param1 with you
// param1 name and value with your one's)
writer.write("sender_no=" + phno);
writer.flush();
String responseString = "";
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
responseString = responseString.concat(line);
}
con.disconnect();
return responseString;
}
how could i make tcp connection .right now i don't have any idea . i am new to android and java aswell so any sample code about the tcp connection would be appreciated
To create a TCP Connection you need to Use Socket:
Socket socket = new Socket(host_name_or_ip_address, port_no);
To Send Data use socket.getOutputStream()
To Receive Data use socket.getInputStream()
Just replace HttpURLConnection with Socket. It works pretty much the same

Categories

Resources