InputStream returns java.io.FileNotFoundException - android

Im trying to download file from webservice.
the method is post and im sending json to service.
this is my code :
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
DataOutputStream printout;
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestMethod("POST");
conn.connect();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("Id", 25);
// Send POST output.
printout = new DataOutputStream(conn.getOutputStream ());
printout.writeUTF(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();
int status = conn.getResponseCode();
// getting file length
int lenghtOfFile = conn.getContentLength();
Log.d("lenghtOfFile : ", lenghtOfFile + "byte");
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream());
// Output stream to write file
OutputStream output = new FileOutputStream("backup.db");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.toString());
}
return null;
}
status code is 200 and the size of lenghtOfFile is the file im trying to
download , but at this line :
InputStream input = new BufferedInputStream(url.openStream());
program gives error :
05-28 09:11:25.513: E/Error:(627): java.io.FileNotFoundException: http://example.com/api/Values
i even changed the buffer size to content size but still no hope.

Related

How can i upload video using android youtube api?

i'm trying to make a andoid application using youtube.
i'd like to upload a video using URL.
with my codes, i received 200 http status code and success message, but actually it doesn't.
how can i resolve it?
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("PUT");
conn.setRequestProperty("Authorization", String.format("Bearer %s", access_token));
conn.setRequestProperty("Content-Type", "video/*");
conn.setRequestProperty("Content-Length", ContentLength);
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
int numberBytes = fis.available();
byte bytearray[] = new byte[numberBytes];
Log.e(" FileLength", String.valueOf(bytearray.length));
for(int i = 0; i < bytearray.length; i++)
dos.write(bytearray[i]);
dos.flush();
fis.close();
dos.close();
int responseCode = conn.getResponseCode();
if(responseCode == 200) {
Log.e("ResponseCode", String.valueOf(responseCode));
InputStream is = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] byteBuffer = new byte[1024];
byte[] byteData = null;
int nLength = 0;
while((nLength = is.read(byteBuffer, 0, byteBuffer.length)) != -1) {
baos.write(byteBuffer, 0, nLength);
}
byteData = baos.toByteArray();
String response = new String(byteData);
Log.e("RESPONSE", response);
}
} catch(Exception e) {
e.printStackTrace();
}
Use this library project
The code is a reference implementation for an Android OS application that captures video, uploads it to YouTube,
Detailed Answer: uploading using above library project

Application/octet-stream

I need to pass an image in application/octet-stream format. I think it means binary image data. How can I convert my drawable to this format?
Here is the code where I'll pass this data in the place of body :
StringEntity reqEntity = new StringEntity("{body}");
You can use HttpURLConnection, something like this:
Long BUFFER_SIZE = 4096;
String method = "POST";
String filePath = "FILE_NAME"
File uploadFile = new File(filePath);
if (!(uploadFile.isFile() && uploadFile.exists())) {
println 'File Not Found !!!!'
return;
}
URL url = new URL("http://your_url_here/" + uploadFile.name);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
String contentType = "application/octet-stream"
httpConn.setDoOutput(true);
httpConn.setRequestMethod(method);
httpConn.setRequestProperty("Accept", "*/*");
httpConn.setRequestProperty("Content-type", contentType);
OutputStream outputStream = httpConn.getOutputStream();
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
println "Response message : "+httpConn.getResponseMessage();

Cannot send binary data using multipart form (string params + video param + image param)

I ran into a problem while trying to send some binary files(a 1.44 MB video and a png Image) along with some string params by using multipart-form. The problem is that after writing the headers and all the necessary stuff , when writing bytes on outputstream it blocks me from writing something else .
Can you please tell me what am i doing wrong !!
Here is my AsyncTask that sends data to the server
private class UploadUpAsyncTask extends AsyncTask<String, Void,
String>{
private String path;
private String lineend ="\r\n";
private String boundry = "****";
private String twoHiphens="--";
int bytesRead,bytesAvailable,bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
public UploadUpAsyncTask(String path){
this.path =path;
}
#Override
protected String doInBackground(String... urls) {
File file = new File(path);
File image = new File("/storage/emulated/0/DCIM/100MEDIA/error.png");
try {
URL url = new URL(urls[0]);
Log.d("UPLOAD", "URL ="+urls[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundry);
conn.setRequestProperty("Authorization", "----------------------------");
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"user_id\""+lineend+lineend);
out.writeBytes("1"+lineend);
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"preview_id\""+lineend+lineend);
out.writeBytes("1"+lineend);
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"categories_id\""+lineend+lineend);
out.writeBytes("2"+lineend);
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"title\""+lineend+lineend);
out.writeBytes("Mama"+lineend);
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"tags\""+lineend+lineend);
out.writeBytes("mama"+lineend);
out.flush();
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"video\"; filename=\""+file.getName()+"\""+lineend);
out.writeBytes(lineend);
Log.d("UPLOAD", "Titlul video-ului ="+file.getName());
//decoding of bytes from video
FileInputStream file_stream = new FileInputStream(file);
bytesAvailable =file_stream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
buffer = new byte[bufferSize];
Log.d("UPLOAD", "Bytes Read Video =" +bytesRead);
bytesRead = file_stream.read(buffer);
//writting to outputstream
while (bytesRead >0){
out.write(buffer, 0, bytesRead);
bytesRead=file_stream.read(buffer);
}
Log.d("UPLOAD", "Done Loading first buffer");
file_stream.close();
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"thumb\"; filename=\""+image.getName()+"\""+lineend);
out.writeBytes(lineend);
Log.d("UPLOAD", "Titlul preview-ului ="+image.getName());
//decodint image bytes
FileInputStream image_stream = new FileInputStream(image);
int bytesRead2;
int bytesAvailable2, bufferSize2 ;
bytesAvailable2 = image_stream.available();
bufferSize2 = Math.min(bytesAvailable2, maxBufferSize);
byte []buffer2 = new byte[bufferSize2];
//writing to outputstream
bytesRead2 = image_stream.read(buffer2);
while(bytesRead2>0){
out.write(buffer2, 0, bytesRead2); // bytesAvailable2 = image_stream.available();
bytesRead2 = image_stream.read(buffer2);
}
image_stream.close();
Log.d("UPLOAD", "Done loading the second buffer");
out.writeBytes(twoHiphens+boundry+twoHiphens+lineend);
out.writeBytes(lineend);
out.flush();
out.close();
Log.d("UPLOAD","Response Code = "+conn.getResponseCode());
String responseMessage = conn.getResponseMessage();
Log.d("UPLOAD", "Response Message = "+responseMessage);
InputStream in;
if(conn.getResponseCode() >= 400){
in = conn.getErrorStream();
}else{
in = conn.getInputStream();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
StringBuilder response = new StringBuilder();
char []bytes = new char[512];
int read ;
while((read = reader.read(bytes))!=-1){
response.append(bytes, 0, read);
}
Log.d("UPLOAD", "Response " +response);
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "maine";
}
#Override protected void onPostExecute(String result) {
super.onPostExecute(result); Log.d("UPLOAD", "Upload complete");
}
}
SOLVED !! The MIME Type selection of the files sent on the server was all wrong !

input stream error

Here is a strange error I face, while trying to download a file, I need to open the input stream and then write data read into the output stream...The Input Stream does not work...there is no error while debugging..but it just seems to hang there and F6 on the keyboard does not seem to work....Have to terminate the debug session...What am I doing wrong???
try{
URL url = new URL(pdfurl);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("k", "Lenght of file: " + lenghtOfFile);
//InputStream s=file
InputStream s=url.openStream();
InputStream input = new BufferedInputStream(s);
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch (Exception e)
{
download_flag = true;
String s=e.getMessage().toString();
Log.d("k","exception occured"+s);
}
you could try an HttpGet request:
HttpGet httpGet = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
// Execute HTTP Get Request
HttpResponse response = httpclient.execute(httpGet);
content = response.getEntity().getContent();

file not found exception

i am working in android. i want to integrate foursquare with my application.
for functioning of check in at a place. i am using this following code:-
URL url = new URL("https://api.foursquare.com/v2/checkins/add/");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader rd = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
}
but this is generating file not found exception. please help me what mistake i have done.
thank you in advance.
Try with following approach
read and write data from URL
void readAndWriteFromWeb(){
//make connection
URL url = new URL("https://api.foursquare.com/v2/checkins/add/");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setAllowUserInteraction(true);
httpURLConnection.setRequestProperty("Connection", "keep-alive");
httpURLConnection.setRequestProperty("ConnectionTimeout", "12000");
httpURLConnection.setRequestProperty("Content-Length", "" + request.length);
//write data
OutputStream out = httpURLConnection.getOutputStream();
out.write(request);
out.flush();
//Log.e("Request URL "+url, "Request Data "+request);
//read data
InputStream inputStream = httpURLConnection.getInputStream();
int length = httpURLConnection.getContentLength();
//Log.e("Content Length", "" + length);
int readLength = 0;
int chunkSize = 1024;
int readBytes = 0;
byte[] data = new byte[chunkSize];
StringBuilder builder = new StringBuilder();
while((readBytes = inputStream.read(data)) != -1){
builder.append(new String(data,0,readBytes).trim());
readLength += readBytes;
//Release the memory.
data = null;
//Check the remaining length
if((length - readLength) < chunkSize){
if((length - readLength) == 0){
break;
}
data = new byte[((length) - readLength)];
}else{
data = new byte[chunkSize];
}
}
}

Categories

Resources