I'm trying to write to a text file on my web server using HttpURLConnection.getOutputStream(). I have tried this on two different servers without success.
I have added a FileWriter to test the InputStream, and that file is created on a local directory correctly, but nothing is showing up on the in the web server directory, even with all password protection off.
Any help would be greatly appreciated.
URL url;
try {
url = new URL("http://www.myWebsite.com/myFile.txt");
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
try {
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
OutputStream in = new BufferedOutputStream(urlConnection.getOutputStream());
InputStream fin1;
try {
fin1 = new FileInputStream(Environment.getExternalStorageDirectory() + "/fileToRead.txt");
FileWriter fWriter = new FileWriter(Environment.getExternalStorageDirectory() + "/fileToWrite.txt");
int data = fin1.read();
while(data != -1) {
fWriter.write(data);
in.write(data);
data = fin1.read();
}
fWriter.flush();
fWriter.close();
fin1.close();
in.flush();
in.close();
} catch (FileNotFoundException e31) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
} catch (IOException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
}
} catch (MalformedURLException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
}
You have to call getInputStream() on the urlConnection in order to get the output stream to flush out the socket to the remote server.
See the discussion here: Why do you have to call URLConnection#getInputStream to be able to write out to URLConnection#getOutputStream?
You are catching the IOException (Right after the IOException) but are not doing anything with it. At least print the stack trace.
You can also use Apache's Http Client http://hc.apache.org/httpcomponents-client-ga/index.html
Much easier than getting URLConnection to work.
Related
I'm trying to modify a doc with Apache POI in Java.
At first the test.doc cannot be read with a exception raised up :
"org.apache.poi.poifs.filesystem.NotOLE2FileException: Invalid header signature; read 0x6576206C6D783F3C, expected 0xE11AB1A1E011CFD0 - Your file appears not to be a valid OLE2 document
"
So I saved the doc as "word 97 - 03" format,and then POI can read the doc properly.
But when I try to rewrite the content to a new file with nothing changed, the file output.doc cannot be opened by MS Office.
When I make a new doc myself with MS Office, the POI works well, everything goes right.
So the problem is "test.doc".
The test.doc is generated by some sort of a program which I can't access the code,so I don't know what goes wrong.
My question is :
1.As test.doc can be read by MS Office why can't POI without saving as a new format doc?
2.As the POI can read the doc, why it cannot write back to a new file(MS Office can't open)?
Here is my code:
FileInputStream fis = null;
try {
fis = new FileInputStream("test.doc");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
POIFSFileSystem pfs = null;
try {
pfs = new POIFSFileSystem(fis);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HWPFDocument hwdf = null;
try {
hwdf = new HWPFDocument(pfs);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("output.doc"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
hwdf.write(fos);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
}
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
pfs.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The HEX stuff read as ASCII and read little-endian converts to <?xml ve, which indicates that test.doc is some other format than actually .doc/.docx.
Word will open other data-formats gracefully sometimes, upon saving it will be saved correctly in the Word-Format.
Therefore you will need to use a hex-editor to take a look at the contents of test.doc and if it is really in some broken format you need to find out where it is coming from and how the creation of that file can be fixed.
I am developing an android app that reads a webpage using AsyncTask.I have 2 AsyncTask classes that reads different page, one inside service, other not.In both cases url connection method is enclosed inside try-catch block , but their catch blocks are different(TimeoutException catch block missing in the 2nd AsyncTask class, tried to catch or throw it manually but failed) .Even though their connection methods are same, their try-catch blocks are different, but I need to catch TimeoutException in both task.
Here is part of my 1st AsyncTask class
try {
url=new URL(link);
huc=(HttpURLConnection) url.openConnection();
huc.setRequestMethod("GET");
huc.setDoOutput(true);
huc.setReadTimeout(READ_TIMEOUT);
huc.connect();
dothework();
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
showErrorMsg();
e.printStackTrace();
}
and part of 2nd AsyncTask class
try {
url = new URL(link);
HttpURLConnection huc=(HttpURLConnection) url.openConnection();
huc.setReadTimeout(5000);
huc.setDoOutput(true);
huc.setRequestMethod("GET");
huc.connect();
}catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(ctx, e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
I'm not sure, but I think a HttpConnection is a AsyncTask already. So, I think you're making a call to an AsyncTask inside another.
I am getting a HTTP response code 405 when I use HttpURLConnection to make a DELETE request:
public void makeDeleteRequest(String objtype,String objkey)
{
URL url=null;
String uri="http://localhost:8180/GoogleMapsLoadingTest/rest/GoogleMapsErp/";
HttpURLConnection conn=null;
try {
url=new URL(uri);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
conn=(HttpURLConnection) url.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn.setDoInput(true);
conn.setDoOutput(true);
try {
System.out.println(conn.getResponseCode());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
conn.setRequestMethod("DELETE");
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
How can I make this request?
The 405 status code means that your method (DELETE) is not allowed for the resource you specified; in this case, what looks like an entire REST endpoint directory. You should use DELETE on the specific item you want deleted; perhaps you forgot to actually use the method parameters when constructing the URL?
It would appear to be a problem with your server. I'm guessing nginx, but let me know if not.
Take a look here to see how to compile ngninx with HttpDavModule. There are other servers that have issues with this, but nginx doesn't have it by default.
If you're running Apache, check your module configurations to see if you're disallowing them or not. Here's a post about a previous solution. Unfortunately, this problem is typically specific to modules that have been installed. On a vanilla installation, however, you can often just allow for DELETE (see your config file, as well as the OP of that link)
I am getting the occassional error message when I try to read a serialized object from a file. It works fine 9 times out of 10, but for some reason I get lots of these error message sin the catlog:
06-01 23:57:50.824: ERROR/MemoryFile(16077): MemoryFile.finalize() called while ashmem
still open
and
06-01 23:57:57.664: ERROR/MemoryFile(16077): java.io.IOException: munmap failed
The second message comes with no indication where the exception is caused. (Clearly when I'm loading the file, but I already have a try/catch around it.)
My loadfile method looks like this:
public TGame loadSavedGame(){
TGame g=null;
InputStream instream = null;
BufferedReader br=null;
InputStreamReader inputreader=null;
try {
File sdCard = Environment.getExternalStorageDirectory();
instream = new
FileInputStream(sdCard.getAbsolutePath()+"/egyptica/serializationtest");
// inputreader = new InputStreamReader(instream);
// br= new BufferedReader(inputreader);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
try {
ObjectInputStream ois = new ObjectInputStream(instream);
try {
g= (TGame) ois.readObject();
try {
instream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return g;
} catch (ClassNotFoundException ex) {
// TODO Auto-generated catch block
android.util.Log.e("DESERIALIZATION FAILED (CLASS NOT
FOUND):"+ex.getMessage(), "ex");
ex.printStackTrace();
return null;
}
} catch (StreamCorruptedException ex) {
android.util.Log.e("DESERIALIZATION FAILED (CORRUPT):"+ex.getMessage(),
"ex");
// TODO Auto-generated catch block
ex.printStackTrace();
return null;
} catch (IOException ex) {
android.util.Log.e("DESERIALIZATION FAILED (IO
EXCEPTION):"+ex.getMessage(), "ex");
// TODO Auto-generated catch block
ex.printStackTrace();
return null;
}
}
One possibility I have thought of is using a BufferedReader to rea the file. However I'm not sure how to go about doing this. Any help would be appreciated.
Try to put finally block after try and put there closing statements for your streams and also useful thing is to use:
FileInputStream.getFD().sync();
It makes sure that file really received your close/flush
Having some issue with Android 2.3 not picking up the Content-Encoding header from our server.
See http://pastebin.com/v0Jvn0nD for a comparison with 2.2 and 2.3.
So, I am trying to get a workaround so Android can handle the GZIP, at the moment it just fails. Here is the connection logic:
Any help would be cool. Many thanks
URL test = null;
try {
test = new URL(url);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
URLConnection connection = null;
try {
connection = test.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream stream = null;
try {
stream = connection.getInputStream();
Log.d("HttpHelper","getContentEncoding: " + connection.getContentEncoding()); // RETURNING NULL ON 2.3
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if ("gzip".equals(connection.getContentEncoding())) { // NULL HERE ON 2.3
try {
stream = new GZIPInputStream(stream);
responseString = textHelper.getText(stream);
globallistener.onComplete(responseString);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}