Upload a file using HTTP put in Java - java

I am writing a desktop app in Java to upload a file to a folder on IIS server using HTTP PUT.
URLConnection urlconnection=null;
try{
File file = new File("C:/test.txt");
URL url = new URL("http://192.168.5.27/Test/test.txt");
urlconnection = url.openConnection();
urlconnection.setDoOutput(true);
urlconnection.setDoInput(true);
if (urlconnection instanceof HttpURLConnection) {
try {
((HttpURLConnection)urlconnection).setRequestMethod("PUT");
((HttpURLConnection)urlconnection).setRequestProperty("Content-type", "text/html");
((HttpURLConnection)urlconnection).connect();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
BufferedOutputStream bos = new BufferedOutputStream(urlconnection
.getOutputStream());
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
file));
int i;
// read byte by byte until end of stream
while ((i = bis.read()) >0) {
bos.write(i);
}
System.out.println(((HttpURLConnection)urlconnection).getResponseMessage());
}
catch(Exception e)
{
e.printStackTrace();
}
try {
InputStream inputStream;
int responseCode=((HttpURLConnection)urlconnection).getResponseCode();
if ((responseCode>= 200) &&(responseCode<=202) ) {
inputStream = ((HttpURLConnection)urlconnection).getInputStream();
int j;
while ((j = inputStream.read()) >0) {
System.out.println(j);
}
} else {
inputStream = ((HttpURLConnection)urlconnection).getErrorStream();
}
((HttpURLConnection)urlconnection).disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This program creates an empty file on the destination folder (Test). The contents are not written to the file.
What is wrong with this program?

After you complete the loop where you are writing the BufferedOutputStream, call bos.close(). That flushes the buffered data before closing the stream.

Possible bug: bis.read() can return a valid 0. You'll need to change the while condition to >= 0.

Related

How to send a file using PUT method to a web service

I am trying to upload a file using PUT method. I have been advised before to use POST and do a multipart upload but my web service only allows GET, PUT, PATCH, DELETE, HEAD and OPTIONS. And the main reason for that is that I am updating the JSON array that contains id, target, source, file. Now I just have to update the file part in the web service i.e. I have to upload the file there.
Here is my code:
URLConnection urlconnection = null;
try{
File file = new File("/Users/pathtofile/file.pdb");
URL url = new URL("http://example.website/api/jobs/5/");
urlconnection = url.openConnection();
urlconnection.setDoOutput(true);
urlconnection.setDoInput(true);
if (urlconnection instanceof HttpURLConnection) {
try {
((HttpURLConnection)urlconnection).setRequestMethod("PUT");
((HttpURLConnection)urlconnection).setRequestProperty("Content-Type",
"application/json");
((HttpURLConnection)urlconnection).connect();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
System.out.println("ProtocolException");
e.printStackTrace();
}
}
BufferedOutputStream bos = new BufferedOutputStream(urlconnection
.getOutputStream());
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
file));
int i;
// read byte by byte until end of stream
while ((i = bis.read()) >= 0) {
bos.write(i);
}
bos.close();
// Getting error here (Bad request).
System.out.println(((HttpURLConnection)urlconnection).getResponseMessage());
} catch(Exception e) {
System.out.println("Exception");
e.printStackTrace();
}
try {
InputStream inputStream;
int responseCode = ((HttpURLConnection)urlconnection).getResponseCode();
if ((responseCode >= 200) && (responseCode <= 202)) {
inputStream = ((HttpURLConnection)urlconnection).getInputStream();
int j;
while ((j = inputStream.read()) >= 0) {
System.out.println(j);
}
} else {
System.out.println(responseCode);
inputStream = ((HttpURLConnection)urlconnection).getErrorStream();
System.out.println(inputStream);
}
((HttpURLConnection)urlconnection).disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("IOException");
e.printStackTrace();
}
And I get the following error:
Bad Request
400
Is there a way to send a file using PUT method? The file is going to be in a place lıke this:
{"target":["This field is required."],
"project":["This field is required."],
"option":["This field is required."],
"result_file":["No file was submitted."],
"com_status":["This field is required."]}
The above is output from curl PUT method that I tried without giving any parameters. And it also shows that the parameters are required in a JSON format.

reading deflated data from the stream using inflater and InflaterInputStream

I'm trying to send a deflated string over http, when I use compression and decompression on the server side, without using streams, it's ok but when I write it to stream like this:
byte[] deflatedData = mtext.getByte();
try {
t.sendResponseHeaders(200,deflatedData.length);
} catch (IOException e1) {
display(e1);
e1.printStackTrace();
if(closeafter){
t.close();
}
return;
}
DeflaterOutputStream os = new DeflaterOutputStream(t.getResponseBody());
try {
os.write(deflatedData ,0,deflatedData .length);
} catch (IOException e1) {
mByte = null;
display(e1);
if(closeafter){
t.close();
}
return;
}
os.flush();
os.close();
and read from client side like this:
InflaterInputStream ini = new
InflaterInputStream(response.body().byteStream());
ByteArrayOutputStream bout =new ByteArrayOutputStream(512);
int b;
while ((b = ini.read()) != -1) {
bout.write(b);
}
ini.close();
bout.close();
String s=new String(bout.toByteArray());
android decompresses like this:
public static byte[] decompress(byte[] data) throws IOException, DataFormatException{
Inflater inflater = new Inflater();
inflater.setInput(data);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
byte[] buffer = new byte[1024];
while (!inflater.finished()) {
int count = inflater.inflate(buffer);
outputStream.write(buffer, 0, count);
}
byte[] output = outputStream.toByteArray();
outputStream.close();
inflater.end();
return output;
}
so I get the following exception:
java.util.zip.DataFormatException: data error
Where am I going wrong?
The sending part was totally ok , The answer was to Use InflaterInputStream Directly from the input stream , like this:
public static String ReadDeflatedData(InputStream input){
InflaterInputStream in = new InflaterInputStream(input, new Inflater());
int bytesRead=0;
StringBuilder sb = new StringBuilder();
byte[] contents = null;
try {
contents = new byte[in.available()];
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
while( (bytesRead = in.read(contents)) != -1){
sb.append(new String(contents, 0, bytesRead));
}
} catch (IOException e) {
System.out.println(e.toString());
e.printStackTrace();
}
try {
return new String(sb.toString().getBytes(),"UTF-8");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

How to read string from php to android studio (java)

I don't know why i get a null value when i call the GetPHPData() function. The "out" variable returns nothing (""). I make a Toast.makeTest and it returns empty string. Please help. This is my code:
public class PHPConnect extends Activity
{
String url = "http://122.2.8.226/MITBookstore/sqlconnect.php";
HttpURLConnection urlConnection = null;
String out = null;
public String GetPHPData()
{
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(10000);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
out = readStream(in);
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
finally
{
urlConnection.disconnect();
return out;
}
}
private String readStream(BufferedReader is)
{
try
{
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int i = is.read();
while(i != -1)
{
bo.write(i);
i = is.read();
}
return bo.toString();
} catch (IOException e)
{
return e.getMessage();
}
}
}
By the way, im running a wamp server and I port forwarded my router, on local host, the url works, but on remote connection, it won't return a string. You can try out the url, the result is: "This is the output:emil"
Can you please try below piece of code which is working for me, also add INTERNET permission in android manifest file. Still if it is not working then may be issue with server end then try to debug it.
URL url;
try {
url = new URL("myurl");
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

FileInputStream unmarshalling, but HttpInputStream won't in Java

I can marhsall XML from a file when I read it from disk, but when I download it via the web I get this error.
[org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Premature end of file.]
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.createUnmarshalException
I assume the web input stream contains additional information or something?
Works
InputStream inputStream = null;
try {
inputStream = new FileInputStream(filePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Doesnt Work
InputStream inputStream = null;
try {
inputStream = new URL(url).openStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
BulkDataRecordType bulkDataRecordType = getObjectFromXml(inputStream);
In another class
public BulkDataRecordType getObjectFromXml(InputStream inputStream)
{
try {
JAXBContext jc = JAXBContext.newInstance(BulkDataRecordType.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
bulkDataRecordType = (BulkDataRecordType) unmarshaller.unmarshal(inputStream);
} catch (JAXBException e1) {
e1.printStackTrace();
}
I am first checking the checksum of the string. Once I commented this out it worked. I found a solution to create two new streams and it worked. If you have a better solution let me know.
public byte[] getCheckSumFromFile(InputStream inputStream)
{
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
InputStream is = null;
try {
is = new DigestInputStream(inputStream, md);
}
finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return md.digest();
}
Create Two Streams From Original
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) > -1 ) {
byteArrayOutputStream.write(buffer, 0, len);
}
byteArrayOutputStream.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
// Get check sum of downloaded file
byte[] fileCheckSum = getCheckSumFromFile(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));

Programmatically downloading files pushed through a PHP page

Some PHP sites use a page to act as a middle man for handling file downloads.
With a browser this works transparently. There seems to a be a slight pause while the php page processes the request.
However, attempting a download through Java using a URL or HttpURLConnection returns a plain html page. How could I get the file downloads working in the same way?
Edit: Here is an example link:
http://depot.eice.be/index.php?annee_g=jour&cours=poo
Edit: Here is some of the code I've been testing:
// This returns an HTML page
private void downloadURL(String theURL) {
URL url;
InputStream is = null;
DataInputStream dis;
String s;
StringBuffer sb = new StringBuffer();
try {
url = new URL(theURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
if (conn.getResponseCode()!=HttpURLConnection.HTTP_OK)
return;
InputStream in = conn.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int i;
while ((i = in.read()) != -1) {
bos.write(i);
}
byte[] b = bos.toByteArray();
FileOutputStream fos = new FileOutputStream( getNameFromUrl( theURL ) );
fos.write(b);
fos.close();
conn.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// This will throw Exceptions if the URL isn't in the expected format
public String getNameFromUrl(String url) {
int slashIndex = url.lastIndexOf('/');
int dotIndex = url.lastIndexOf('.');
System.out.println("url:" + url + "," + slashIndex + "," + dotIndex);
if (dotIndex == -1) {
return url.substring(slashIndex + 1);
} else {
try {
return url.substring(slashIndex + 1, url.length());
} catch (StringIndexOutOfBoundsException e) {
return "";
}
}
}
Considering no other constrains, you can read the redirected URL from the HTTP header and connect to that URL directly from JAVA.
There is an API setting to follow redirects automatically – but it should be true by default. How do you access the URL?
See Java API docs...
I think I've found a solution using HttpUnit. The source of the framework is available if you wish to see how this is handled.
public void downloadURL(String url) throws IOException {
WebConversation wc = new WebConversation();
WebResponse indexResp = wc.getResource(new GetMethodWebRequest(url));
WebLink[] links = new WebLink[1];
try {
links = indexResp.getLinks();
} catch (SAXException ex) {
// Log
}
for (WebLink link : links) {
try {
link.click();
} catch (SAXException ex) {
// Log
}
WebResponse resp = wc.getCurrentPage();
String fileName = resp.getURL().getFile();
fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
System.out.println("filename:" + fileName);
File file = new File(fileName);
BufferedInputStream bis = new BufferedInputStream(
resp.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file.getName()));
int i;
while ((i = bis.read()) != -1) {
bos.write(i);
}
bis.close();
bos.close();
}
System.out.println("Done downloading.");
}

Categories