I made a HTML server using com.sun.net.httpserver library. I want to send a jar file to the client to make them download it.
This method below actually make the client download the file:
#Override
public void handle(HttpExchange httpExchange) {
File file = new File("Test.jar");
try {
httpExchange.sendResponseHeaders(200, file.length());
OutputStream outputStream = httpExchange.getResponseBody();
Files.copy(file.toPath(), outputStream);
outputStream.close();
} catch (IOException exception) {
exception.printStackTrace();
}
}
but it sends the jar file as a zip. How do I get it to send it as a jar file instead? And is there a better way to send files?
Please try adding the following to get correct filename for the download:
httpExchange.getResponseHeaders().add("Content-Disposition", "attachment; filename=Test.jar");
You might also want do add the following to get the corrent content-type:
httpExchange.setAttribute(HTTPExchange.HeaderFields.Content_Type.toString(), "application/java-archive");
Please see https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types for a listing of content-types for different suffixes.
Last 3 days I started to learn Spring. I want to send a image from the phone gallery to the spring server. I want to mention that the server is local so I'm using localhost. I saw a tutorial that if I want to send stuff to a local server, the server address is my laptop address + the port (ex. 8080) and I have to connect the phone to the same Wi-Fi as the laptop.
I know how to get the image from the gallery but I don't know how to send it. Many solutions from stackoverflow are old and some classes got deprecated and I can't try their method.
Also, what should I do in the spring controller to receive the image?
You'll have use MultipartFile to upload an image using spring. Please go through following example.
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String fileUpload(#RequestParam("file") MultipartFile file) {
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
//save file in server - you may need an another scenario
Path path = Paths.get("/" + file.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
//redirect to an another url end point
return "redirect:/upload-status";
}
Please make sure you can reach to your computer through your mobile device. I believe you may know that Android requires additional privilege to use network connections. So make sure you have permitted your app to access network.
EDIT:
You can use HttpClient to upload file from your mobile app. Please try following code.
HttpClient httpClient = AndroidHttpClient.newInstance("App");
HttpPost httpPost = new HttpPost("http://your-server-url");
httpPost.setEntity(new FileEntity(new File("your-file-path"), "application/octet-stream"));
HttpResponse response = httpClient.execute(httpPost);
I need play video from samba to android device streaming. I've been look for this question and someone say that :
Using JCIFS to scan for and "see" the share: http://jcifs.samba.org/
Implementing a simple HTTP server (NanoHttpd) to stream the content
via http: https://github.com/NanoHttpd/nanohttpd
Passing the http://localhost/myvideo link to the VideoView
I'm already use JCIFS to get SmbFile in my project and I also get inputstream( smbfile.getInputStream() ).
Now I import NanoHttpd and I create simple HTTP server that http address ishttp://localhost:8080
private class MyHTTPD extends NanoHTTPD {
public MyHTTPD() throws IOException {
super(8080);
}
#Override
public Response serve(String uri, String method, Properties header, Properties parms, Properties files) {
InputStream is = new SmbFile(filePath,auth).getInputStream();
//return index as response
return new NanoHTTPD.Response(HTTP_OK, "video/mp4", is);
}
}
server = new MyHTTPD();
server.start();
But my http address is different from http://localhost/myvideo, I don't know how to get right http address and put it in to VideoView.
I don't know how to get path like http://localhost/myvideo .
Thanks for help....
The other question : Can I use VideoView playing video from InputStream ?
I was trying to use the Apache Ant Get task to get a list of WSDLs generated by another team in our company. They have them hosted on a weblogic 9.x server on http://....com:7925/services/. I am able to get to the page through a browser, but the get task gives me a FileNotFoundException when trying to copy the page to a local file to parse. I was still able to get (using the ant task) a URL without the non-standard port 80 for HTTP.
I looked through the Ant source code, and narrowed the error down to the URLConnection. It seems as though the URLConnection doesn't recognize the data is HTTP traffic, since it isn't on the standard port, even though the protocol is specified as HTTP. I sniffed the traffic using WireShark and the page loads correctly across the wire, but still gets the FileNotFoundException.
Here's an example where you will see the error (with the URL changed to protect the innocent). The error is thrown on connection.getInputStream();
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class TestGet {
private static URL source;
public static void main(String[] args) {
doGet();
}
public static void doGet() {
try {
source = new URL("http", "test.com", 7925,
"/services/index.html");
URLConnection connection = source.openConnection();
connection.connect();
InputStream is = connection.getInputStream();
} catch (Exception e) {
System.err.println(e.toString());
}
}
}
The response to my HTTP request returned with a status code 404, which resulted in a FileNotFoundException when I called getInputStream(). I still wanted to read the response body, so I had to use a different method: HttpURLConnection#getErrorStream().
Here's a JavaDoc snippet of getErrorStream():
Returns the error stream if the
connection failed but the server sent
useful data nonetheless. The typical
example is when an HTTP server
responds with a 404, which will cause
a FileNotFoundException to be thrown
in connect, but the server sent an
HTML help page with suggestions as to
what to do.
Usage example:
public static String httpGet(String url) {
HttpURLConnection con = null;
InputStream is = null;
try {
con = (HttpURLConnection) new URL(url).openConnection();
con.connect();
//4xx: client error, 5xx: server error. See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
boolean isError = con.getResponseCode() >= 400;
//In HTTP error cases, HttpURLConnection only gives you the input stream via #getErrorStream().
is = isError ? con.getErrorStream() : con.getInputStream();
String contentEncoding = con.getContentEncoding() != null ? con.getContentEncoding() : "UTF-8";
return IOUtils.toString(is, contentEncoding); //Apache Commons IO
} catch (Exception e) {
throw new IllegalStateException(e);
} finally {
//Note: Closing the InputStream manually may be unnecessary, depending on the implementation of HttpURLConnection#disconnect(). Sun/Oracle's implementation does close it for you in said method.
if (is != null) {
try {
is.close();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
if (con != null) {
con.disconnect();
}
}
}
This is an old thread, but I had a similar problem and found a solution that is not listed here.
I was receiving the page fine in the browser, but got a 404 when I tried to access it via the HttpURLConnection. The URL I was trying to access contained a port number. When I tried it without the port number I successfully got a dummy page through the HttpURLConnection. So it seemed the non-standard port was the problem.
I started thinking the access was restricted, and in a sense it was. My solution was that I needed to tell the server the User-Agent and I also specify the file types I expect. I am trying to read a .json file, so I thought the file type might be a necessary specification as well.
I added these lines and it finally worked:
httpConnection.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
httpConnection.setRequestProperty("Accept","*/*");
check the response code being returned by the server
I know this is an old thread but I found a solution not listed anywhere here.
I was trying to pull data in json format from a J2EE servlet on port 8080 but was receiving the file not found error. I was able to pull this same json data from a php server running on port 80.
It turns out that in the servlet, I needed to change doGet to doPost.
Hope this helps somebody.
You could use OkHttp:
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
I've tried that locally - using the code provided - and I don't get a FileNotFoundException except when the server returns a status 404 response.
Are you sure that you're connecting to the webserver you intend to be connecting to? Is there any chance you're connecting to a different webserver? (I note that the port number in the code doesn't match the port number in the link)
I have run into a similar issue but the reason seems to be different, here is the exception trace:
java.io.FileNotFoundException: http://myhost1:8081/test/api?wait=1
at sun.reflect.GeneratedConstructorAccessor2.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at sun.net.www.protocol.http.HttpURLConnection$6.run(HttpURLConnection.java:1491)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.protocol.http.HttpURLConnection.getChainedException(HttpURLConnection.java:1485)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1139)
at com.doitnext.loadmonger.HttpExecution.getBody(HttpExecution.java:85)
at com.doitnext.loadmonger.HttpExecution.execute(HttpExecution.java:214)
at com.doitnext.loadmonger.ClientWorker.run(ClientWorker.java:126)
at java.lang.Thread.run(Thread.java:680)
Caused by: java.io.FileNotFoundException: http://myhost1:8081/test/api?wait=1
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1434)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:379)
at com.doitnext.loadmonger.HttpExecution.execute(HttpExecution.java:166)
... 2 more
So it would seem that just getting the response code will cause the URL connection to callGetInputStream.
I know this is an old thread but just noticed something on this one so thought I will just put it out there.
Like Jessica mentioned, this exception is thrown when using non-standard port.
It only seems to happen when using DNS though. If I use IP number I can specify the port number and everything works fine.
I need to upload a file using Apache fileupload with ProgressListener but alongwith that I also need to show the progressbar for the upload status.
Actual requirement is I just need to parse a local XML file parse the xml into appropriate objects and put them in Database. Do I really need to upload the file to server to get it parsed. As I am getting exception like file not found on remote server while it runs fine on my local m/c.
Any quick help would be appreciated.
Thanks in advance !!!
If you have access to the server side, I advise to debug the upload process. The exception suggests that you want to open the file on the server based on the uploaded file name. On your local machine this works, because it runs on the same file system. On the server side, the Apache FileUpload receives binary data, which needs to be extracted from the request data stream:
#Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (ServletFileUpload.isMultipartContent(request)) {
FileItemFactory factory = new DiskFileItemFactory(Integer.MAX_VALUE, null);
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request);
for (FileItem item : items) {
byte[] data = item.get();
// do something with the binary data
}
} else {
System.err.println("Not a multipart/form-data");
}
}
And also you need the form to be:
<form name='frm' method="POST" action='UploadServlet'
id="frm" enctype="multipart/form-data">
From your description it sounds like your servlet is trying to read the file from the filesystem itself, based on the filename submitted in the form. This isn't going to work if the servlet is running on a different machine to where the file is.
Make sure your servlet is getting the file contents from the fileupload API, not from the local filesystem.