file not found exception - android

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];
}
}
}

Related

How to get PDF file from HttpUrlConnection response in Android Java?

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();
}

How To Create And Send Multipart Request With Text file In Android

I need to fetch data from this site http://www.speech.cs.cmu.edu/cgi-bin/tools/lmtool/run
But I am getting this "[ERRO] Problems with your corpus; cannot continue. Please check diagnostics [0 0]" When I am trying to send text file to site.
Here is my code:
String fileUrl = "/sdcard/fish.txt";
File logFileToUpload = new File(fileUrl);
final String BOUNDERY = "------WebKitFormBoundary4Pn8WfAaV8Bv3qqy";
final String CRLF = "\r\n";
// MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
StringBuilder sbBody_1 = new StringBuilder();
sbBody_1.append(BOUNDERY + CRLF);
sbBody_1.append("Content-Disposition: form-data; name=\"formtype\"" + CRLF);
sbBody_1.append(CRLF);
sbBody_1.append("simple");
sbBody_1.append(BOUNDERY + CRLF);
sbBody_1.append("Content-Disposition: form-data; name =\"corpus\""+"filename=\"fish\"" + CRLF);
//sbBody_1.append("Content-Disposition: form-data; filename=\"fish\"" + CRLF);
String str1="aaa";
sbBody_1.append(CRLF);
//sbBody_1.append(str1);
//sbBody_1.append(CRLF);
//sbBody_1.append(BOUNDERY + "--" );
StringBuilder sbBody_2 = new StringBuilder();
//sbBody_2.append("pratik");
sbBody_2.append(BOUNDERY + "--" );
URL url = new URL("http://www.speech.cs.cmu.edu/cgi-bin/tools/lmtool/run");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
// connection.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary4Pn8WfAaV8Bv3qqy");
// connection.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(connection.getOutputStream());
out.write(sbBody_1.toString().getBytes());
//byte[] bFile = new String(getBytesFromFile(Files1)).getBytes();
// System.out.println(""+bFile);
FileInputStream inputStreamToLogFile = new FileInputStream(logFileToUpload);
int bytesRead;
byte[] dataBuffer = new byte[1024];
while((bytesRead = inputStreamToLogFile.read(dataBuffer)) != -1) {
out.write(dataBuffer, 0, bytesRead);
System.out.println("output"+dataBuffer +bytesRead);
}
out.write(sbBody_2.toString().getBytes());
//out.write(CRLF.getBytes());
out.flush();
out.close();
BufferedReader bips = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String temp = null;
while ((temp = bips.readLine()) != null) {
System.out.println("output"+temp);
((TextView) findViewById(R.id.textview1))
.setText(temp);
}
bips.close();
connection.disconnect();
It's better to use OkHttp for network requests. You can try this example for multipart request.
Thank you for your help #MaxV i sloved my issue by using OkHttp and POSTMAN

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();

How to read variable amount of json data from url?

I am using the following code to read json data from url , but it has fixed length of 500 for the json data. How can I ensure that all the data(variable length) is always read.
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
Thanks.
Reference
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String newLine = System.getProperty("line.separator");
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + newLine);
}
String result = sb.toString();
byte[] data = new byte[1024];
int bytesRead = inputstream.read(data);
while(bytesRead != -1) {
doSomethingWithData(data, bytesRead);
bytesRead = inputstream.read(data);
}

Categories

Resources