I am getting pdf file in response of API, I am using HttpUrlConnection (Android Java). I am unable to get pdf file from the response.
My code to get response is:
URL url = new URL(RESULT_DOWNLOAD_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setAllowUserInteraction(false);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setConnectTimeout(90000);
connection.setReadTimeout(90000);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/pdf");
connection.setRequestProperty("Accept", "application/pdf");
connection.setRequestProperty("access-token", resultAccessToken);
connection.setChunkedStreamingMode(1024);
connection.connect();
JSONObject jsonObject = new JSONObject();
jsonObject.put("reference",reference);
DataOutputStream os = new DataOutputStream(connection.getOutputStream());
byte[] payload = jsonObject.toString().getBytes(StandardCharsets.UTF_8);
int progressPercent = 0;
int offset = 0;
int bufferLength = payload.length / 100;
while(progressPercent < 100) {
os.write(payload, offset, bufferLength);
offset += bufferLength;
++progressPercent;
this.publishProgress(progressPercent);
}
os.write(payload, offset, payload.length % 100);
os.flush();
os.close();
int responseCode = connection.getResponseCode();
if ((responseCode >= HttpURLConnection.HTTP_OK)
&& responseCode < 300) {
inputStream = connection.getInputStream();
resultResponse = inputStreamToString(inputStream);
Log.d(TAG, "Response : " + resultResponse);
}
private static String inputStreamToString(InputStream inputStream) throws IOException {
StringBuilder out = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
reader.close();
return out.toString();
}
Response is like(for understanding, I converted it in string form):
I want to download file from this response, response is returning pdf file.
Add this code...
int responseCode = connection.getResponseCode();
if ((responseCode >= HttpURLConnection.HTTP_OK)
&& responseCode < 300) {
inputStream = connection.getInputStream();
String FolderPath = "Images/"
File folder = null;
if(Build.VERSION.SDK_INT >= 29){ //Build.VERSION_CODES.R
folder = new File(context.getFilesDir() + "/" + FolderPath);
}else {
folder = new File(
Environment.getExternalStorageDirectory() + "/"
+ FolderPath);
}
if (!folder.exists())
folder.mkdirs();
String FilePath = folder.getAbsolutePath() + "/"
+ Path.substring(Path.lastIndexOf('/') + 1);
OutputStream output = new FileOutputStream(FilePath, false);
byte data[] = new byte[8192];
int count = -1;
while ((count = inputStream.read(data)) != -1) {
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
inputStream.close();
}
Related
I have tried relentlessly to create a succesfull file upload from my JAVA/Android project to Django/Python backend.
The file I am trying to upload is a wav audio file which is stored on the phone.
I am trying to mix two sets of code.
The Android code I am using is the one taken from: How to upload a WAV file using URLConnection.
public class curlAudioToWatson extends AsyncTask<String, Void, String> {
String asrJsonString="";
#Override
protected String doInBackground(String... params) {
String result = "";
try {
Log.d("Msg","**** UPLOADING .WAV to ASR...");
URL obj = new URL(ASR_URL);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
//conn.setRequestProperty("X-Arg", "AccessKey=3fvfg985-2830-07ce-e998-4e74df");
conn.setRequestProperty("Content-Type", "audio/wav");
conn.setRequestProperty("enctype", "multipart/form-data");
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
String wavpath=mRcordFilePath;
File wavfile = new File(wavpath);
boolean success = true;
if (wavfile.exists()) {
Log.d("Msg","**** audio.wav DETECTED: "+wavfile);
}
else{
Log.d("Msg","**** audio.wav MISSING: " +wavfile);
}
String charset="UTF-8";
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "\r\n"; // Line separator required by multipart/form-data.
OutputStream output=null;
PrintWriter writer=null;
try {
output = conn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
byte [] music=new byte[(int) wavfile.length()];//size & length of the file
InputStream is = new FileInputStream (wavfile);
BufferedInputStream bis = new BufferedInputStream (is, 16000);
DataInputStream dis = new DataInputStream (bis); // Create a DataInputStream to read the audio data from the saved file
int i = 0;
copyStream(dis,output);
}
catch(Exception e){
}
conn.connect();
int responseCode = conn.getResponseCode();
Log.d("Msg","POST Response Code : " + responseCode + " , MSG: " + conn.getResponseMessage());
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Log.d("Msg","***ASR RESULT: " + response.toString());
JSONArray jresponse=new JSONObject(response.toString()).getJSONObject("Recognition").getJSONArray("NBest");
asrJsonString=jresponse.toString();
for(int i = 0 ; i < jresponse.length(); i++){
JSONObject jsoni=jresponse.getJSONObject(i);
if(jsoni.has("ResultText")){
String asrResult=jsoni.getString("ResultText");
//ActionManager.getInstance().addDebugMessage("ASR Result: "+asrResult);
Log.d("Msg","*** Result Text: "+asrResult);
result = asrResult;
}
}
Log.d("Msg","***ASR RESULT: " + jresponse.toString());
} else {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Log.d("Msg","POST FAILED: " + response.toString());
result = "";
}
} catch (Exception e) {
Log.d("Msg","HTTP Exception: " + e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}
#Override
protected void onPostExecute(String result) {
if(!result.equals("")){
Log.d("Msg","onPostEXECUTE SUCCESS, consuming result");
//sendTextInputFromUser(result);
//ActionManager.getInstance().addDebugMessage("***ASR RESULT: "+asrJsonString);
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}else{
Log.d("Msg","onPostEXECUTE FAILED" );
}
}
}
public void copyStream( InputStream is, OutputStream os) {
final int buffer_size = 4096;
try {
byte[] bytes = new byte[buffer_size];
int k=-1;
double prog=0;
while ((k = is.read(bytes, 0, bytes.length)) > -1) {
if(k != -1) {
os.write(bytes, 0, k);
prog=prog+k;
double progress = ((long) prog)/1000;///size;
Log.d("Msg","UPLOADING: "+progress+" kB");
}
}
os.flush();
is.close();
os.close();
} catch (Exception ex) {
Log.d("Msg","File to Network Stream Copy error "+ex);
}
}
The Django backend code is taken from: https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html and I am using the simple upload:
def simple_upload(request):
if request.method == 'POST' and request.FILES['myfile']:
myfile = request.FILES['myfile']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
return render(request, 'core/simple_upload.html', {
'uploaded_file_url': uploaded_file_url
})
return render(request, 'core/simple_upload.html')
I have already disabled the need for CSRF using #csrf_exempt.
I am getting the error "MultiValueDictKeyError" since Java does not post the file with the name 'myfile' for request.FILES['myfile'] to catch. Is have tried removing the ['myfile'] and just use request.FILES but then I get an error on
filename = fs.save(myfile.name, myfile)
saying there is no name to fetch.
Can I post the file so that it it catched by
request.FILES['myfile']
or is there better/simpler Django backend-code to use for communication with Android/IOS.
Thanks in advance and I apologize if this is a stupid question but I am dead stuck.
Here I go again answering my own question.
I found the following code from Android:How to upload .mp3 file to http server?
Using that instead of How to upload a WAV file using URLConnection and changing the line: dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName + "\"" + lineEnd);
To dos.writeBytes("Content-Disposition: form-data; name=\"myfile\";filename=\"" + existingFileName + "\"" + lineEnd);
fixed my problem.
I am wondering here and there from last 2 days. My issue is that I am sending multiple files with some text/plain fields using multipart/form-data.
The issue is that when I am sending data using HTTPCLient its working fine but when I am trying to send data using HTTPURLConnection, server is not receiving anything, below is my MultipartUtility,
public class MultipartUtils extends NetworkUtility
{
private static final String END_REQUEST = "--";
private String mBoundary;
public MultipartUtils()
{
mBoundary = END_REQUEST + "quAxBSd";
}
public HttpURLConnection getUrlConnection(String URL, String httpMethod,
String contenttype, String boundry) throws Exception
{
URL url = new URL(URL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
if (httpMethod.equalsIgnoreCase(HTTP_GET) == false)
urlConnection.setDoInput(true);
else
urlConnection.setDoInput(false);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestMethod(httpMethod);
if (contenttype.equalsIgnoreCase(APPLICATION_MULTIPART))
{
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundry);
urlConnection.setRequestProperty("ENCTYPE", "multipart/form-data");
}
else
{
urlConnection.setRequestProperty("Content-Type", contenttype);
}
return urlConnection;
}
public String uploadImagesAddPost(Activity mContext, String URL, String jsonString, ArrayList<ImageListBean> mImageBeanList) throws Exception
{
HttpURLConnection httpURLConnection = getUrlConnection(URL, HTTP_POST, APPLICATION_MULTIPART, mBoundary);
httpURLConnection.connect();
DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
PrintWriter writer = new PrintWriter(new OutputStreamWriter(dataOutputStream, UTF8),
true);
addJsonToPart(writer, jsonString);
for (int i = 0; i < mImageBeanList.size(); i++)
{
try
{
byte[] imageByteArray = {};
Uri imageUri = mImageBeanList.get(i).getmUri();
String imagePath = ImageCaputureUtility.getPath(imageUri, mContext);
if (!imagePath.equals(""))
{
if (mImageBeanList.get(i).getmType().equalsIgnoreCase(MellTooConstants.IMG))
{
//For img
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, outputStream);
imageByteArray = outputStream.toByteArray();
addFileAsByte(dataOutputStream, "imageview" + (i + 1), imageByteArray, ("imageview" + (i + 1)) + ".jpeg", IMAGE_JPEG);
}
else
{
//For video
/* Uploading thumb*/
Bitmap bitmap = UtilsMellToo.createThumb(imageUri, mContext);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, outputStream);
imageByteArray = outputStream.toByteArray();
addFileAsByte(dataOutputStream, "imageview4", imageByteArray, "imageview4" + ".jpeg", IMAGE_JPEG);
/* Uploading video*/
imageByteArray = MellTooUtil.readFileToByteArray(new File(imagePath));
addFileAsByte(dataOutputStream, "video", imageByteArray, "video" + (i + 1) + ".mp4", VIDEO_MP4);
}
}
else
{
//No need to upload data
}
}
catch (Exception e)
{
e.printStackTrace();
}
if (i + 1 != mImageBeanList.size())
writer.append(mBoundary).append(CHANGE_LINE);
}
writer.append(mBoundary + END_REQUEST);
writer.flush();
return getResponse(httpURLConnection);
}
private void addJsonToPart(PrintWriter writer, String text)
{
writer.append(mBoundary).append(CHANGE_LINE);
writer.append(CONTENT_DISPOSITION + FORM_DATA + NAME + "\"formstring\"").append(CHANGE_LINE);
writer.append(CONTENT_TYPE + PLAIN_TEXT + CHARSET + UTF8).append(CHANGE_LINE);
writer.append(CONTENT_TRANSFER_ENCODING + "8bit").append(CHANGE_LINE);
writer.append(text).append(CHANGE_LINE);
writer.flush();
}
public void addFileAsByte(DataOutputStream outputStream, String fieldName, byte[] imageByteArray, String fileName, String contentType) throws IOException
{
PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, UTF8),
true);
writer.append(mBoundary).append(CHANGE_LINE);
writer.append(CONTENT_DISPOSITION + FORM_DATA + NAME + "\"" + fieldName + "\";" + FILE_NAME + "\"" + fileName + "\"").append(CHANGE_LINE);
writer.append(CONTENT_TYPE + contentType).append(CHANGE_LINE);
writer.append(CONTENT_TRANSFER_ENCODING + BINARY).append(CHANGE_LINE);
writer.flush();
InputStream inputStream = new ByteArrayInputStream(imageByteArray);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.writeBytes(CHANGE_LINE);
outputStream.flush();
inputStream.close();
}
}
Below is the method, how I am using this class,
jsonResponseString = new MultipartUtils()
.uploadImagesAddPost(mContext, AppConstants.BASE_URL + AppConstants.SAVE_POST_URL,
mJsonString, mImageList);
Below is my ASP side,
HttpContextWrapper.Request.Form["formstring"]; //This is returning null
Please help me out from this...!!!
Thanks in advance
Below is my request,
After struggling approximately 4 days, I found the issue was in the boundry and the new line in the request....!
There should be a boundary and a blank line between text and image part and I was not using it. The blank line is separating the header from the boday of the each part of a multipart/form-data request...!
My app has to connect to google drive. The connection works fine.
I can see all the files in the drive. The download of the files works fine.
Unfortunately when I try to open it the files are corrupted or I can't open them at all. Does anyone know a solution for this problem ??
enter code here
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
fileName = mr.getTitle();
// opens input stream from the HTTP connection
// URLConnection connection = url.openConnection();
String saveFilePath = saveDir + File.separator + fileName;
InputStream inputStream = httpConn.getInputStream();
FileOutputStream outputStream = new
FileOutputStream(saveFilePath);
// opens an output stream to save into file
int bytesRead = 0;
// int read;
byte[] buffer = new byte[16384];
// while ((bytesRead = inputStream.read(buffer)) > 0) {
// outputStream.write(buffer, 0, bytesRead);
// }
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out
.println("No file to download. Server replied HTTP code: "
+ responseCode);
}
httpConn.disconnect();
It's problem between your file length and byte buffer. For quickly, please change to and retry
byte[] buffer = new byte[1024];
or you could get the length of input stream then create buffer
long streamLength = inputStream.available();
byte[] buffer = new byte[streamLength];
Have fun!
I'm trying to download a file in my app, but the download times are inconsistently too long.
Sometimes it just downloading it in normal time, but sometimes it just stuck for like 30 seconds or more until it will just fail due to time out error.
Why would that be?
private void Download(String url, String destFileName) throws IOException{
//TODO remove that
// File file = new File(destFileName);
// if(file.exists())
// return;
if(BuildConfig.DEBUG)
Log.d("DownloadFile", "Downloading url: " + url + ", dest: " + destFileName);
HttpGet httppost = null;
AndroidHttpClient client = AndroidHttpClient.newInstance("TvinciAndroid");
FileOutputStream fos = new FileOutputStream(destFileName);
try {
httppost = new HttpGet(url);
HttpResponse res = client.execute(httppost);
if (res.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
Header[] headers = res.getHeaders("Location");
if(headers != null && headers.length != 0) {
url = headers[headers.length - 1].getValue();
Download(url, destFileName);
}
}
HttpEntity responseEntity = res.getEntity();
if (responseEntity != null && responseEntity.getContentLength() > 0) {
InputStream is = AndroidHttpClient.getUngzippedContent(responseEntity);
BufferedReader reader = new BufferedReader(new InputStreamReader(is,Charset.forName("UTF-8")));
StringBuilder bld = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
line += "\n";
fos.write(line.getBytes());
bld.append(line);
}
reader.close();
if(BuildConfig.DEBUG)
Log.d("file content", bld.toString());
bld = null;
}
}
catch(IOException ex){
throw ex;
}
finally {
client.close();
fos.close();
}
}
Any help will be much appreciated
Try specifying the buffer to 8192.
//input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
I have a sample working code here that can download a file via URL It is different from your implementation, but this might help you.
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
// getting file length
int lengthOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream(filePath);
byte data[] = new byte[1024];
long total = 0;
pDialog.setMax(lengthOfFile);
NOTIFICATION_ID = 1+lengthOfFile;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
//publishProgress(""+(int)((total*100)/lenghtOfFile));
publishProgress(""+(int)(total));
notifBuilder.setProgress(lengthOfFile, (int)(total), false)
.setContentText("Download in progress... "+total+"/"+lengthOfFile);
nm.notify(NOTIFICATION_ID, notifBuilder.build());
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
Log.e("Error: ", e.getMessage());
return e.getMessage()+" download failed!";
}
I Hope this helps.
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];
}
}
}