I try to read json file from the URL in my Android Project. But strange situation happens. StringBuilder successfully gets first few characters but then I get java.net.SocketException: recvfrom failed: EBADF (Bad file descriptor)
Why I get this exception?
What is wrong with my code?)
JSON: http://inlyfortesting.ucoz.net/artists.json
My JSONParser:
public JSONArray getJSONFromUrl(String urlAsString) {
// try to create JSONObject from string
try {
URL url = new URL(urlAsString);
new DownloadFileTask().execute(url).get();
jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return jObj;
}
private class DownloadFileTask extends AsyncTask<URL, Integer, Long> {
StringBuilder sb;
protected Long doInBackground(URL... urls) {
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) urls[0].openConnection();
is = new BufferedInputStream(connection.getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
connection.disconnect();
}
//file reading
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
sb = new StringBuilder();
int symbol;
int counter = 0;
while ((symbol = reader.read()) != -1) { //PROBLEM HERE
sb.append((char)symbol); //OR HERE
}
json = sb.toString();
is.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace(); //java.net.SocketException: recvfrom failed: EBADF (Bad file descriptor)
}
return null;
}
}
You're disconnecting the connection before you read from it. You need to do that afterwards.
Surely this is obvious?
Related
I'm show data from database but is not work.
That is get me the Exception : FileNotFound but the path is well.
But when I put the URL from the browser it works normally
There is my code :
#Override
protected String doInBackground(String... parametro)
{
try
{
URL url = new URL(urlMostrarClientes);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer buffer = new StringBuffer();
String linha = "";
while ((linha = bufferedReader.readLine()) != null)
{
buffer.append(linha + "\n");
}
inputStream.close();
bufferedReader.close();
progressDialog.dismiss();
return buffer.toString().trim();
} catch (MalformedURLException e)
{
e.printStackTrace();
progressDialog.dismiss();
Log.v("vampiro","ERRO : " + e.toString());
} catch (ProtocolException e)
{
e.printStackTrace();
progressDialog.dismiss();
Log.v("vampiro","ERRO : " + e.toString());
} catch (IOException e) {
e.printStackTrace();
progressDialog.dismiss();
Log.v("vampiro","ERRO : " + e.toString());
}
return "ERRO";
}
Three ways of solving problem :
file:///yourFilePath
Paths.get(yourPath).toUri().toURL() //java nio way
File(“path_to_file”).toURI().toURL();
//java io way
I'm trying to do a "PUT" request with Android Studio.
But, actually, it doesn't work, I received a "404 not found" whereas I got all the needed infos.
String url = "https://[...]";
URL obj = null;
try {
obj = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection con = null;
DataOutputStream dataOutputStream = null;
try {
con = (HttpURLConnection) obj.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
// optional default is GET
try {
con.setRequestMethod("PUT");
con.setDoInput(true);
con.setDoOutput(true);
System.out.println("Info User to update : " + params[0]);
con.setRequestProperty("X-Auth-Token", params[0].get("token"));
[...]
con.setRequestProperty("shop_id", params[1].get("id"));
dataOutputStream = new DataOutputStream(con.getOutputStream());
OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
osw.flush();
osw.close();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (dataOutputStream != null) {
try {
dataOutputStream.flush();
dataOutputStream.close();
} catch (IOException exception) {
exception.printStackTrace();
}
}
}
int responseCode = 0;
try {
responseCode = con.getResponseCode();
} catch (IOException e) {
e.printStackTrace();
}
If I try the request on Symfony (web app), it's worked well, but with the code, not anymore... Do you see any problems with my request ?
Problem solved, I was able to do what I wanted using a PATCH request instead.
I have this code:
public void uploadToFTP(File file) {
try {
final ByteArrayInputStream stream = new ByteArrayInputStream(FileUtils.readFileToByteArray(file));
String date = dateFormat.format(new Date());
String filename = date.replaceAll(":", "-");
sessionFactory.getSession().write(stream, "dir/" + filename + ".txt");
} catch (IOException e) {
e.printStackTrace();
}
}
The parameter I got in this case File I want to upload to some FTP, but the problem each time I do this the file actually is empty. When I try for example final ByteArrayInputStream stream = new ByteArrayInputStream("Text here".getBytes()); it is working fine, and stores the information inside the file, what could be the problem here, may I have problem maybe with converting the File to bytes or ?
Use thsi code :
public List<ProcessedFile> uploadFTPFilesByCridational(List<ProcessedFile> processedFiles, String sourceDir,
String destinationPath, String hostName, String userName, String password, String portNo, String extation,
int fileHours, int fileMint) {
List<ProcessedFile> processedFilesList = new ArrayList<>();
try {
FTPClient ftpClient = new FTPClient();
// client FTP connection
ftpClient = connectToFTPClient(hostName, userName, password, portNo);
// check if FTP client is connected or not
if (ftpClient.isConnected()) {
if (processedFiles != null && processedFiles.size() > 0) {
for (ProcessedFile processedFile : processedFiles) {
FileInputStream inputStream = null;
try {
File file = new File(sourceDir + "/" + processedFile.getOriginalFileName());
inputStream = new FileInputStream(file);
if (!ftpClient.isConnected()) {
ftpClient = connectToFTPClient(hostName, userName, password, portNo);
}
ByteArrayInputStream in = null;
try {
ftpClient.changeWorkingDirectory(destinationPath);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
in = new ByteArrayInputStream(FileUtils.readFileToByteArray(file));
ftpClient.storeFile(file.getName(), in);
} catch (Exception e) {
logger.error(e.getMessage());
}
inputStream.close();
in.close();
processedFile.setProcessedStatus(ProcessedStatus.COMPLETED);
processedFilesList.add(processedFile);
} catch (Exception e) {
logger.error(e);
processedFile.setProcessedStatus(ProcessedStatus.FAILED);
processedFilesList.add(processedFile);
}
}
}
}
if (ftpClient.isConnected()) {
try {
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException e) {
logger.error(e.getMessage());
} finally {
try {
ftpClient.disconnect();
} catch (Exception e) {
logger.error(e.getMessage());
}
}
}
} catch (Exception e) {
logger.error("FTP not connected exception: " + e);
}
return processedFilesList;
}
I have a json file that I am sending to the server as a POST but it has to be gzipped
I dont know how to do it
I found the potential solution here GZip POST request with HTTPClient in Java
but I dont know how to merge the methodology they used in the second part of the answer with my makeHttpRequest method (they are using a multipart entity and Im using a urlencoded entity)
EDIT: Here is how I get jsonAsBytes
public static byte[] stringToGZIPByteArray (String string) {
Log.d("string to be gzipped", string);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null;
try {
gzos = new GZIPOutputStream(baos);
gzos.write(string.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (gzos != null) {
try {
gzos.close();
} catch (IOException ignore) {
};
}
}
return baos.toByteArray();
} // End of stringToGZIPByteArray
This is where I use that method
jsonParser.sendGzippedJSONviaHTTP(context, API.JSON_ACCEPT, UtilityClass.stringToGZIPByteArray(jsonObject.toString()), context.getResources());
and this is sendGzippedJSONviaHTTP
public JSONObject sendGzippedJSONviaHTTP(Context context, String url, byte[] gzippedJSON, Resources res) {
if (httpClient == null) {
try {
httpClient = new HttpClientBuilder().setConnectionTimeout(10000)
.setSocketTimeout(60000) //
.setHttpPort(80)//
.setHttpsPort(443)//
.setCookieStore(new BasicCookieStore())//
.pinCertificates(res, R.raw.keystore, null) //
.build();
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// Making HTTP request
try {
// request method is POST
// defaultHttpClient
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Encoding", "gzip");
httpPost.setHeader("Content-Type", "application/json");
httpPost.setEntity(AndroidHttpClient.getCompressedEntity(gzippedJSON, context.getContentResolver()));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
reader.close();
json = sb.toString();
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jsonObject = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
// return JSON String
return jsonObject;
} // End of makeHttpRequest
Take a look at AndroidHttpClient. You can use it instead of appache's DefaultHttpClient. It has a static method getCompressedEntity(byte[] data, ContentResolver resolver)
So, you can write:
HttpPost httpPost = new HttpPost(url);
post.setEntity( AndroidHttpClient.getCompressedEntity( jsonAsBytes, null ) );
httpClient.execute(httpPost);
UPDATE:
this is the code from AndroidHttpClient:
public static AbstractHttpEntity getCompressedEntity(byte data[], ContentResolver resolver)
throws IOException {
AbstractHttpEntity entity;
if (data.length < getMinGzipSize(resolver)) {
entity = new ByteArrayEntity(data);
} else {
ByteArrayOutputStream arr = new ByteArrayOutputStream();
OutputStream zipper = new GZIPOutputStream(arr);
zipper.write(data);
zipper.close();
entity = new ByteArrayEntity(arr.toByteArray());
entity.setContentEncoding("gzip");
}
return entity;
}
should give you some insights
I am trying to get an Audio file through http get from a secure restful service, I have successfully receive and parse text XML service but a bit confused that how to do with Audio file.
code to call the secure restful service with XML response
String callWebService(String serviceURL) {
// http get client
HttpClient client = getClient();
HttpGet getRequest = new HttpGet();
try {
// construct a URI object
getRequest.setURI(new URI(serviceURL));
} catch (URISyntaxException e) {
Log.e("URISyntaxException", e.toString());
}
// buffer reader to read the response
BufferedReader in = null;
// the service response
HttpResponse response = null;
try {
// execute the request
response = client.execute(getRequest);
} catch (ClientProtocolException e) {
Log.e("ClientProtocolException", e.toString());
} catch (IOException e) {
Log.e("IO exception", e.toString());
}
try {
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
} catch (IllegalStateException e) {
Log.e("IllegalStateException", e.toString());
} catch (IOException e) {
Log.e("IO exception", e.toString());
}
StringBuffer buff = new StringBuffer("");
String line = "";
try {
while ((line = in.readLine()) != null) {
buff.append(line);
}
} catch (IOException e) {
Log.e("IO exception", e.toString());
return e.getMessage();
}
try {
in.close();
} catch (IOException e) {
Log.e("IO exception", e.toString());
}
// response, need to be parsed
return buff.toString();
}
may this one help you..
public static void downloadFile(String fileURL, String fileName) {
try {
// fileURL=fileURL.replaceAll("amp;", "");
Log.e(fileURL, fileName);
String RootDir = Environment.getExternalStorageDirectory()
.toString();
File RootFile = new File(RootDir);
new File(RootDir + Commons.dataPath).mkdirs();
File file = new File(RootFile + Commons.dataPath + fileName);
if (file.exists()) {
file.delete();
}
file.createNewFile();
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File(
"mnt/sdcard"+Commons.dataPath + fileName));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
}