I want to set up the REST API to support file downloads via Java (The java part is not needed at the moment -- I am saying it in here so you can make your answer more specific for my problem).
How would I do that?
For example, I have this file in a folder (./java.jar), how can I stream it in such a way for it to be downloadable by a Java client?
I forgot to say that this, is for some paid-content.
My app should be able to do this
Client: Post to server with username,pass.
Rest: Respond accordingly to what user has bought (so if it has bought that file, download it)
Client: Download file and put it in x folder.
I thought of encoding a file in base64 and then posting the encoded result into the usual .json (maybe with a nice name -- useful for the java application, and with the code inside -- though I would not know how I should rebuild the file at this point). <- Is this plausible? Or is there an easier way?
Also, please do not downvote if unnecessary, although there is no code in the question, that doesn't mean I haven't researched it, it just means that I found nothing suitable for my situation.
Thanks.
What you need is a regular file streaming, using a valid URL.
Below code is an excerpt from here
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
For your needs, based on your updated comments on the above answer, you could call your REST endpoint after user logs in(with Auth and other headers/body you wish to receive) and proceed to the download.
Convert your jar/downloadable content to bytes. More on this
Java Convert File to Byte Array and visa versa
Later, in case if you dont want regular streaming as aforementioned in previous answers, you can put the byte content in the body as Base64 String. You can encode to Base64 from your byte array using something like below.
Base64.encodeToString(byte[], Base64.NO_WRAP + Base64.URL_SAFE);
Reference from here: How to send byte[] and strings to a restful webservice and retrieve this information in the web method implementation
Again, there are many ways to do this, this is one of the ways you can probably do using REST.
Related
I have produced a little app that searches and displays for me data which I retrieve from Google Books in a neat but simple fashion. Everything works so far, but there is an issue directly at the source: Though Google provides me correctly with German text search results, it for some reason displays all special German characters (Ä, Ö, Ü and ß probably) as the "�" dummy or sometimes just "?".
I was able to confirm that the JSONObject built from the InputStream already contains those mistakes. It seems like the original inputstream from Google is not being read correctly. Weird is that I have "UTF-8" encoding (which should contain german characters) added to my InputStreamReader, but to no avail apparently.
Here is the http-request procedure I am using:
public class HttpRequest {
public static String request(String urlString) throws IOException {
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(10000);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
StringBuilder builder = new StringBuilder();
String inputLine;
while((inputLine = in.readLine()) != null)
builder.append(inputLine);
in.close();
return builder.toString();
}
}
What else could be going wrong? I checked the StringBuilder already, but the mistakes are already in the inputLine(s) that get read out of the BufferedReader.
Also, I was unable to find any language or encoding specific settings in the official google books api guide, so I guess they should come with universal encoding, but then the "UTF-8" flag should detect them, or not?
Easiest is to check the raw data in another way, such as a browser. Looking at a Google Books api url response in the browser is quite simple, just use the url and the response comes back as json. Optionally install a json viewer plugin, but not needed for this.
For example use this url:
https://www.googleapis.com/books/v1/volumes?q=Latein+key=NO
Checking the http header (in the browser developer tools for example) you can see that the header list the content as having the expected encoding:
content-type: application/json; charset=UTF-8
Look at the specific content for some German results and the text there and we can see that it is correct German special characters for some books, but not for all. Depending on the book in question.
Conclusion: UTF-8 is indeed correct and the source/raw data has missing/wrong data for some texts for the German characters.
I am using DataOutputStream class to send my data as post data to a php server
DataOutputStream dataOutputStreamRegister = new DataOutputStream(connectionToRegister.getOutputStream());
dataOutputStreamRegister.writeBytes("txtUserID="+userName+"&txtPassword="+userPassword+"&ddlCountry="+countryId
+"&ddlUniversity="+universityId+"&ddlCourseYear="+courseYearId+"&txtEmail="+userEmail+"&txtInitial="+userInitials
+"&txtFname="+userFirstName+"&txtLname="+userLastName+"&txtDob="+userBirthMonth+"/"+userBirthDay+"/"+userBirthYear
+"&ddlLevel="+levelId+"&txtSkills="+studentSkills+"&ddlGender="+genderId+"&ddlFraternity="+fraternityId+"&ddlSorority="
+sororityId+"&ddlClubs="+paramsText);
The last parameter "ddlClubs" i want to send should be like an array.The code in the php server is as follows
foreach($_POST["ddlClubs"] as $key=>$val){
....
}
How should i go about doing this as many techniques i saw included deprecated classes like "defaultHttpClient" and "NameValuePairs"
Thanks everyone for your time.
Just format your url accordingly:
...&ddlClubs[0]=value0&ddlClubs[1]=value1
This also works with associative arrays, such as:
&ddlClubs[name0]=value0&ddlClubs[name1]=value1
Unfortunately this has its limits as a url has a maximum length, meaning you cannot put a very huge array into the url.
I'm working on a chat application, and I need to process a get request for a file that has been uploaded to the database. I'm not sure if I should return an output stream or a file or what.
The idea is that it will be something like any other chat application where the image appears as message are loaded. Using an output stream seemed like the best option, but I wasn't sure how to create the output stream from the information in the database, which includes an id, checksum, name, size, and mime type.
So my questions are:
How should I approach this?
if output stream is the best way, what's the ideal way to implement it?
Any guidance is appreciated, please let me know if I can make the question more clear, or if more details are necessary to answer the question.
What I couldn't understand how to do is this: serve the image to the front-end/client code. As it turns out, it was super easy.
#GET #javax.ws.rs.Path("/file/{fileId}")
public Response getFile(#Context SecurityContext sc, #PathParam("id") long topicId, #PathParam("fileId") long fileId) {
TopicFile tFile = topicAccessor.getFile(fileId);
String fileLocation = "/server/uploads/" + tFile.getChecksum();
File file = new File(fileLocation);
return Response.ok(file, tFile.getType()).build();
}
Here TopicFile holds metadata for the file in the database, and the files are named their checksum.
So basically the solution to my problem was to return a Response. I hadn't thought of this earlier because I "inherited" this code, and I trusted that the previous person had god reason not to use the Response class.
I am aware that you can use Java to execute the php file from a website like below:
URLConnection conn = new URL("http://localhost/file.php").openConnection();
conn.connect();
However would it be possible to make Java read the php file as a text file and how? (Possibly via the use of the BufferedReader)
Thank you.
If you mean to read the php source, then the answer is no - you cannot read php source in a typical webserver configuration. In most cases it would be very insecure to allow it - passwords and other constants are often stored in php source code.
If however, you are just meaning to read out the result of executing the php document, as a browser would do, you can use something like;
URL u = new URL("http://www.example.com/my/php/doc.php");
URLConnection c = u.openConnection();
InputStream r = c.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(r));
for(String line; (line = reader.readLine()) != null;) System.out.println(line);
To read the source of a remote php document via http, the webserver needs to be configured to not parse & execute the file, rather just serve it blindly as a plain text file.
This can be achieved in a few ways;
Uninstall php - no php engine, no code execution.
Change the file extension - apache actually just identifies files by their file extension, so changing it to .phpsource would do the trick in many instances.
Alter the apache configuration - either globally, or via .htaccess you can alter webserver configurations for a single directory. You would want to do something like php_flag engine off or RemoveHandler .php
Note that only the first, and maybe the second, method above does not open up potential security holes in your server. So use with caution.
I'm using HtmlCleaner to scrape a ISO-8859-1 encoded web site in Android.
I've implemented this in an external jar file that I import into my Android app.
When I run the unit tests in Eclipse it handles Norwegian letters (æ,ø,å) correct (I can verify that in the debugger), but in the Android app these characters look like inverted question marks.
If I attach the debugger to my Android app I can see that these letters are not correct in the exact same places they were good when running unit test from Eclipse, so it's not a display/render/view issue in the Android app.
When I copy the text from the debuggers I get these results:
Java Process (Unit Test): «Blårek», «Benny»
Android Process (In emulator): «Bl�rek», «Benny»
I would expect these Strings to be equal, but notice how the "å" is replaed by the inverted question marks in Android.
I have tried running htmlCleaner.getProperties().setRecognizeUnicodeChars(true) without any luck. Also, I found no way of forcing UTF-8 or ISO-8859-1 encoding in html cleaner, but I' not sure if that would have made a difference.
Here is the code i run:
HtmlCleaner htmlCleaner = new HtmlCleaner();
// connect to url and get root TagNode from HtmlCleaner
InputSteram is = new URL( url ).openConnection().getInputStream();
TagNode rootNode = htmlCleaner.clean( is );
// navigate through some TagNodes, getting the ContentNode
ContentNode cn = rootNode...
// This String contains the incorrectly decoded characters on Android.
// Good in Oracle JVM though..
String value = cn.toString().trim();
Does anyone knows what could cause the decoding behavoir to be different on Android? I guess the main difference between the two environments is that the Android app uses Android's java.io stack while my unit tests use Sun/Oracle's stack.
Thanks,
Geir
HtmlCleaner can't tell what encoding to use; you are passing only the body of the response in the InputStream, but the encoding is in the "content-type" header.
You can set the character encoding on the properties of the HtmlCleaner to the correct encoding from the HTTP connection. But that would require you to parse the correct parameter from the content-type header. Alternatively, you can pass a URL instance to HtmlCleaner and let it manage the connection. Then, it will have access to all the information it needs to decode properly.