Excel file downloaded with Java not readable - java

I am really stuck on this problem and hoping for some help. I automatically log in to a Server and download a Excel (xlsx) File. The download seems to work fine, cause the size is the same as on the server and if I open the file with an XML-Editor it looks valid (compared to other excel Files).
But if I try to open the downloaded file with excel I got a "The file might be corrupt" message and it's not readable.
I tried to change the encoding of the file, the headers of the GET-Request, even tried to write it as Bytestream. Nothing changed.
Here are some relevant code snippets:
public HttpsURLConnection login()
{
HttpsURLConnection connection = null;
String user = "user";
String password = "password";
String authString = user + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
try {
connection = (HttpsURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
connection.setRequestProperty("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//connection.setRequestProperty("Content-Type", "application/vnd.openxml");
connection.setRequestProperty("Accept", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//connection.setRequestProperty("Accept", "application/vnd.openxml");
connection.setRequestProperty("User-Agent", USER_AGENT);
connection.connect();
} catch (IOException e)
{
e.printStackTrace();
}
return connection;
}
The download class
private void sendGet(HttpsURLConnection con) throws Exception {
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
String fileName = "test.xlsx";
file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
}
//use FileWriter to write file
FileWriter fw = new FileWriter(file.getAbsoluteFile());
//BufferedWriter bw = new BufferedWriter(fw);
/**CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
encoder.onMalformedInput(CodingErrorAction.REPORT);
encoder.onUnmappableCharacter(CodingErrorAction.REPORT);**/
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileName), "UTF-8"
));
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
bw.write(inputLine);
}
in.close();
bw.close();
//print result
//System.out.println(response.toString());
}
You can see my attempts in some of the commented lines.
I appreciate any help. Thanks in advance.

Related

How can Upload a file to Sharepoint?

private void uploadDocToSharePoint(String token, Resource resource, String folderName) {
try {
String uploadUrl = Utils.SHARE_POINT_DOMAIN + "_api/web/getfolderbyserverrelativeurl('" + folderName + "')/files/add(url='" + resource.getFilename() + "', overwrite=true)";
URL url = new URL(uploadUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
// Set Header
httpConn.setDoOutput(true);
httpConn.setDoOutput(true);
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Authorization", "Bearer " + token);
httpConn.setRequestProperty("accept", "application/json; odata=verbose");
httpConn.setRequestProperty("Content-Type", "application/xml");
OutputStream os = httpConn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8);
osw.write("Just Some Text");
osw.flush();
osw.close();
os.close(); //don't forget to close the OutputStream
httpConn.connect();
System.out.println(httpConn.getResponseCode());
System.out.println(httpConn.getResponseMessage());
String result;
BufferedInputStream bis = new BufferedInputStream(httpConn.getInputStream());
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result2 = bis.read();
while(result2 != -1) {
buf.write((byte) result2);
result2 = bis.read();
}
result = buf.toString();
System.out.println(result);
} catch (Exception e) {
System.out.println("Error while reading file: " + e.getMessage());
}
}
httpConn.getResponseCode() is 400 and httpConn.getResponseMessage() is Bad Request.
I have tested this request with the URL generated in this class on Postman.
it works correctly.
so I am sure about url and token is correct.
It creates an Empty file successfully.
But as I mentioned the response status is 400 and Bad Request.
I am not sure what is wrong with the following class
Sharepoint guide here
My class copied from here
screenshot here
Pls follow Sharepoint guide here

Rest Api to Decrypt GZIP Body

An API is sending a large amount of data in the body in form of GZIP, I need to create rest API to decrypt and save it in the database, but I am not able to decrypt the data.
`#GetMapping
public void hello() throws IOException {
String payload = "{\n" +
" \"name1\": \"shrikant\",\n" +
" \"date\": \"Fri Apr 05 15:48:59 IST 2019\"\n" +
"}";
String urlStr = "http://localhost:8080/hello";
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(60000);
conn.setConnectTimeout(60000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json");
conn.addRequestProperty("Content-Encoding", "gzip");
OutputStream os = conn.getOutputStream();
GZIPOutputStream gos = new GZIPOutputStream(os);
gos.write(payload.getBytes(StandardCharsets.UTF_8));
System.out.println("payload " +
Arrays.toString(payload.getBytes(StandardCharsets.UTF_8)));
os.close();
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
}`
API to receive the data.
#PostMapping("hello")
public byte[] hello1(HttpServletRequest request) throws IOException {
System.out.println("hi");
ByteArrayInputStream bis = new ByteArrayInputStream();
GZIPInputStream gis = new GZIPInputStream(bis);
BufferedReader br = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while((line = br.readLine()) != null) {
sb.append(line);
}
}
but not able to decrypt data.
how to decrypt request.
On the client side you should close GZIPOutputStream before closing OutputStream.
gos.close();
os.close();
On the server side you should use InputStream from request
ServletInputStream inputStream = request.getInputStream();
GZIPInputStream gis = new GZIPInputStream(inputStream);
BufferedReader br = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while((line = br.readLine()) != null) {
sb.append(line);
}
System.out.println(sb.toString());
For streams better use try-with-resources blok you won't have to remember about closing streams.
try (OutputStream os = conn.getOutputStream()) {
try (GZIPOutputStream gos = new GZIPOutputStream(os)) {
gos.write(payload.getBytes(StandardCharsets.UTF_8));
}
}

Java CURL request using HTTP

I am trying to perform a CURL request using Java. The CURL request is as follows:
curl https://apis.sen.se/v2/feeds/N4hSBSpFlYzXT6ZN2IA1KadgSR9rTazv/events/?limit=1 -u username:password
I am trying to perform the request as follows:
String stringUrl = "https://apis.sen.se/v2/feeds/N4hSBSpFlYzXT6ZN2IA1KadgSR9rTazv/events/?limit=1";
URL url = new URL(stringUrl);
URLConnection uc = url.openConnection();
uc.setRequestProperty("X-Requested-With", "Curl");
String userpass = "username" + ":" + "password";
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
uc.setRequestProperty("Authorization", basicAuth);
InputStreamReader inputStreamReader = new InputStreamReader(uc.getInputStream());
and I am trying to see the contents of inputStreamReader as follows:
int data = inputStreamReader.read();
char aChar = (char) data;
System.out.println(aChar);
The code is compiling and running fine, but it is returning nothing. Where am I going wrong?
I ended up getting it working using the following code:
public static void main(String args[]) throws IOException {
String stringUrl = "url";
URL url = new URL(stringUrl);
URLConnection uc = url.openConnection();
uc.setRequestProperty("X-Requested-With", "Curl");
String userpass = "username" + ":" + "password";
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
uc.setRequestProperty("Authorization", basicAuth);
StringBuilder html = new StringBuilder();
BufferedReader input = null;
try {
input = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String htmlLine;
while ((htmlLine = input.readLine()) != null) {
html.append(htmlLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
input.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(html.toString());
}
I was also trying to do that thing. I have some kind of workaround but it reads everything it sees.
--Here's the code---
String params = "some-parameters";
URL url = new URL("some-website");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
con.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
StringBuffer buffer = new StringBuffer();
while((line = reader.readLine()) != null) {
buffer.append(line+"\n");
}
reader.close();
System.out.print(buffer.toString());
--Notice, I use this code to see if a certain account exist on a certain website, since it outputs everything, what I do is to find a specific regularity upon the code which could tell me if that user exist or not. Well I'm not really even sure if this could help you, but it might be. Good Luck...

Error java.io.FileNotFound BufferReader with InputStreamReader Java Android

I want the get some data from my database on my android application. This is my code:
try{
String nome = (String)arg0[0];
String stato = (String)arg0[1];
String link="http://www.example.org/AndroidPage.php";
String data = URLEncoder.encode("nome", "UTF-8") + "=" + URLEncoder.encode(nome, "UTF-8");
data += "&" + URLEncoder.encode("stato", "UTF-8") + "=" + URLEncoder.encode(stato, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}catch(Exception e){
return new String("exception: " + e.toString());
}
If I comment the BufferReader statement I don't get any error. Here is the error..
(The file exist in the server)
http://i.stack.imgur.com/mb3sc.png
UPDATE:
I resolved the problem.. The error was inside the php script, I forgot to write a semicolon.
Did you add the Internet permission to the manifest?
<uses-permission android:name="android.permission.INTERNET" />

Retrieving imgur upload link after uploading an image through java

So I am using one of the imgur api examples for uploading an image but am stuck on how I retrieve the upload link to view the image.
This is what I have so far, and from what I can tell it uploads it but that itself is not very useful without getting a link to the upload.
This is what I have thus far.
String IMGUR_POST_URI = "http://api.imgur.com/2/upload.xml";
String IMGUR_API_KEY = "MY API KEY";
String file = "C:\\Users\\Shane\\Pictures\\Misc\\001.JPG";
try
{
// Creates Byte Array from picture
ByteArrayOutputStream baos = new ByteArrayOutputStream();
System.out.println("Writing image...");
ImageIO.write(getBufferedImageFromImage(Toolkit.getDefaultToolkit().createImage(file)), "png", baos);
URL url = new URL(IMGUR_POST_URI);
System.out.println("Encoding...");
//encodes picture with Base64 and inserts api key
String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(Base64.encodeBase64String(baos.toByteArray()).toString(), "UTF-8");
data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode(IMGUR_API_KEY, "UTF-8");
System.out.println("Connecting...");
// opens connection and sends data
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
System.out.println("Sending data...");
wr.write(data);
wr.flush();
}
catch(Exception e){e.printStackTrace();}
You should get back either an xml or json with the 'response' to the upload, according to the imgur docs.
I found this little snippet of code that is an example of getting the response after writing to a URL connection, maybe it will help you. This isn't specific to imgur but I think the code should be similar.
public static void main(String[] args) throws Exception {
String stringToReverse = URLEncoder.encode(args[1], "UTF-8");
URL url = new URL(args[0]);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(
connection.getOutputStream());
out.write("string=" + stringToReverse);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
}

Categories