I have tried to connect a PHP script on localHost, but the script isn't accessed without the presence of inputStream. Accidentally I made the code working, but don't know why it is working in presence of inputStream but not in absence of inputStream
try {
String url= "10.0.2.2/arrival.php";
URL loginurl= new URL(url);
HttpURLConnection http= (HttpURLConnection)loginurl.openConnection();
http.setRequestMethod("POST");
http.setDoOutput(true);
http.setDoInput(true);
OutputStream out= http.getOutputStream();
BufferedWriter bfwr= new BufferedWriter(new OutputStreamWriter(out,"UTF-8"));
String post_data= URLEncoder.encode("renter_id","UTF-8")+"="+URLEncoder.encode(renter_id,"UTF-8");
bfwr.write(post_data);
bfwr.flush();
out.close();
bfwr.close();
InputStream inpt= http.getInputStream();
BufferedReader bfrdr= new BufferedReader(new InputStreamReader(inpt,"iso-8859-1"));
String line="";
String result="";
while((line=bfrdr.readLine())!=null){
result+=line;
}
bfrdr.close();
inpt.close();
http.disconnect();
return "";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Related
I'm trying to send a string from my java server to an android client over a socket. Instead of showing the correct String which would be "OK" the read method of the InputStreamReader returns
"��OK".
The code of the server looks like this:
public void run() {
try {
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
dOut.writeUTF("OK");
dOut.flush();
dOut.close();
socket.close();
System.out.println("Disconnected from client number: " + id);
} catch (IOException ex) {
Logger.getLogger(ThreadImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}
And the code of the client looks like this:
public void run() {
try {
Socket socket = null;
try {
socket = new Socket("10.0.2.2", 1978);
} catch (IOException e) {
e.printStackTrace();
}
String serverRes = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
ServerRes = reader.readLine();
System.out.println(ServerRes);
reader.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
You should be using a DataInputStream instead of an InputStreamReader. This is the source of your problem
InputStreamReader reader = new DataInputStream(socket.getInputStream()));
String inStr = reader.readUTF();
I am uploading a file from one server to another server using a Java Program 'POST' method. But I am getting below exception.
java.io.IOException: Error writing to server
at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:582)
at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:594)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1216)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:379)
at com.test.rest.HttpURLConnectionExample.TransferFile(HttpURLConnectionExample.java:107)
at com.test.rest.HttpURLConnectionExample.main(HttpURLConnectionExample.java:44)
I have other method who will authenticate with server. Which will be be called from below code. When I am getting response from server, I am getting above exception. To Transfer a file to server I have written below method. My sample code is below:
public static void TransferFile(){
String urlStr = "http://192.168.0.8:8600/audiofile?path=1/622080256/virtualhaircut.mp3";
File tempFile = new File("/home/MyPath/Workspace/Sample/virtualhaircut.mp3");
BufferedWriter br=null;
HttpURLConnection conn = null;
URL url;
try {
url = new URL(urlStr);
AuthenticationUser();
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", new MimetypesFileTypeMap().getContentType(tempFile.getName()));
} catch (MalformedURLException e1) {
System.out.println("Malformed");
e1.printStackTrace();
} catch (ProtocolException e) {
System.out.println("Protocol");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IO");
e.printStackTrace();
}
System.out.println("line 69");
FileInputStream fis;
OutputStream fos;
try {
System.out.println("line 75");
System.out.println("line 77");
fis = new FileInputStream(tempFile);
fos = conn.getOutputStream();
byte[] buf = new byte[1024 * 2];
int len = 0;
System.out.println("line 80");
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
System.out.println("line 85");
}
System.out.println("line 87");
buf = null;
fos.flush();
fos.close();
fis.close();
}catch (FileNotFoundException e) {
System.out.println("");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (conn.getResponseCode() == 200) {
System.out.println("here");
}
} catch (IOException e) {
e.printStackTrace();
}
}
It is possible that the error ocurred because the receiving server closed the connection, maybe because your file exceeded the size limit. Have you tested with small files?
I've created a small scraping class and the method below reads in the text from a page.
However, I've found that the method fails to close the connection properly. This results in a ton of open connections which cause my hosting company to then suspend my account. Is the below correct?
private String getPageText(String urlString) {
String pageText = "";
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuilder builder = new StringBuilder();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
builder.append(chars, 0, read);
pageText = builder.toString();
} catch (MalformedURLException e) {
Log.e(CLASS_NAME, "getPageText.MalformedUrlException", e);
} catch (IOException e) {
Log.e(CLASS_NAME, "getPageText.IOException", e);
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
Log.e(CLASS_NAME, "getPageText.IOException", e);
}
}
return pageText;
}
Your code is fine in the success case but will potentially leak connections in the failure cases (when the http server returns a 4xx or 5xx status code). In these cases HttpURLConnection provides the response body via .getErrorStream() rather than .getInputStream() and you should make sure to drain and close that stream as well.
URLConnection conn = null;
BufferedReader reader = null;
try {
conn = url.openConnection();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
// ...
} finally {
if(reader != null) {
// ...
}
if(conn instanceof HttpURLConnection) {
InputStream err = ((HttpURLConnection)conn).getErrorStream();
if(err != null) {
byte[] buf = new byte[2048];
while(err.read(buf) >= 0) {}
err.close();
}
}
}
There probably needs to be another layer of try/catch inside that finally but you get the idea. You should not explicitly .disconnect() the connection unless you're sure there won't be any more requests for urls on that host in the near future - disconnect() will prevent subsequent requests from being pipelined over the existing connection, which for https in particular will slow things down considerably.
You are just closing the stream and not the connection, use the following structure:
URL u = new URL(url);
HttpURLConnection conn = (HttpURLConnection)
u.openConnection();
conn.connect();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
and then:
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
Log.e(CLASS_NAME, "getPageText.IOException", e);
}
}
try {
if (conn != null) {
conn.disconnect();
}
} catch (Exception ex) {}
}
My idea is that I want to read an object from a serialized file located in a server. How to do that?
I can only read .txt file using the following code :
void getInfo() {
try {
URL url;
URLConnection urlConn;
DataInputStream dis;
url = new URL("http://localhost/Test.txt");
// Note: a more portable URL:
//url = new URL(getCodeBase().toString() + "/ToDoList/ToDoList.txt");
urlConn = url.openConnection();
urlConn.setDoInput(true);
urlConn.setUseCaches(false);
dis = new DataInputStream(urlConn.getInputStream());
String s;
while ((s = dis.readLine()) != null) {
System.out.println(s);
}
dis.close();
} catch (MalformedURLException mue) {
System.out.println("Error!!!");
} catch (IOException ioe) {
System.out.println("Error!!!");
}
}
You can do this with this method
public Object deserialize(InputStream is) {
ObjectInputStream in;
Object obj;
try {
in = new ObjectInputStream(is);
obj = in.readObject();
in.close();
return obj;
}
catch (IOException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
catch (ClassNotFoundException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
feed it with urlConn.getInputStream() and you'll get the Object. DataInputStream is not fit to read serialized objets that are done with ObjectOutputStream. Use ObjectInputStream respectively.
To write an object to the file there's another method
public void serialize(Object obj, String fileName) {
FileOutputStream fos;
ObjectOutputStream out;
try {
fos = new FileOutputStream(fileName);
out = new ObjectOutputStream(fos);
out.writeObject(obj);
out.close();
}
catch (IOException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
I can pull the user's statuses with no problem with cURL, but when I connect with Java, the xml comes out truncated and my parser wants to cry. I'm testing with small users so it's not choke data or anything.
public void getRuserHx(){
System.out.println("Getting user status history...");
String https_url = "https://twitter.com/statuses/user_timeline/" + idS.rootUser + ".xml?count=100&page=[1-32]";
URL url;
try {
url = new URL(https_url);
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.setReadTimeout(15*1000);
//dump all the content into an xml file
print_content(con);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
System.out.println("Finished downloading user status history.");
}
private void print_content(HttpsURLConnection con){
if(con!=null){
try {
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
File userHx = new File("/" + idS.rootUser + "Hx.xml");
PrintWriter out = new PrintWriter(idS.hoopoeData + userHx);
String input;
while ((input = br.readLine()) != null){
out.println(input);
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
This request doesn't need auth. Sorry about my ugly code. My professor says input doesn't matter so my I/O is a trainwreck.
You have to flush the output stream when you write the content out. Did you flush or close the output stream?