I can't download file with basic http-auth. I have auth string for authorization, but i get exception: FileNotFound.
Code:
URL url = new URL(params[0]);
URLConnection conection = url.openConnection();
conection.setRequestProperty("Authorization", authString);
conection.setRequestMethod("GET");
conection.setAllowUserInteraction(false);
conection.setDoInput(true);
conection.setDoOutput(true);
conection.connect();
int lenghtOfFile = conection.getContentLength();
// Exception on line below
BufferedInputStream input = new BufferedInputStream(conection.getInputStream());
// Output stream
OutputStream output = new FileOutputStream(filePath);
byte data[] = new byte[1024];
...
lenghtOfFile isn't 0. Besides, I tried using HtppClient for this task, but get exception too.
As I have commented, you should remove the line setDoOutput(true) because this is GET request.
Related
I'm using this answer to write into a HttpURLConnection. It works fine and I close the stream and the connection:
MultipartEntityBuilder mb =
MultipartEntityBuilder.create();//org.apache.http.entity.mime
mb.addTextBody("foo", "bar");
mb.addBinaryBody("bin", new File("testFilePath"));
org.apache.http.HttpEntity e = mb.build();
URLConnection conn = new URL("http://127.0.0.1:8080/app").openConnection();
conn.setDoOutput(true);
conn.addRequestProperty(e.getContentType().getName(),
e.getContentType().getValue());//header "Content-Type"...
conn.addRequestProperty("Content-Length",
String.valueOf(e.getContentLength()));
OutputStream fout = conn.getOutputStream();
e.writeTo(fout);//write multi part data...
fout.close();
conn.getInputStream().close();//output of remote url
just fine. However, I would like to know the server's response (json). How would I do that? I tried using:
InputStream input = conn.getInputStream();
String inputString = new Scanner(input, "UTF-8").useDelimiter("\\Z").next();
input.close();
But I get a java.util.NoSuchElementException error.
In the past I've only used the conn.connect() method and then the conn.getInputStream() and it worked fine. Why it doesn't now? How do I fix that error?
I have a server which is sending a .png image to a client via a HTTP post request. The .png is stored inside a sqlite3 database, retrieved as a blob and this all works fine; I have tested saving the returned blob to disk and it can be opened as expected. When my client interprets the response, the payload has mysteriously grown in length from 16365 to 16367, inspecting the response string has shown there are some extra '?' characters intermittently in the stream
Testing the server using the ARC plug-in for Chrome has shown the response received there to be the right length, which leads me to believe there is a problem with my client code:
// request
URL url = new URL(targetURL);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(parameters.getBytes().length));
conn.setRequestProperty("Content-Language", "en-US");
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.getOutputStream().write(parameters.getBytes());
// response
Reader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
for (int c; (c = rd.read()) >=0;)
sb.append((char)c);
String response = sb.toString();
// this String is of length 16367 when it should be 16365
Does anything jump out as being incorrect here? Note I am not doing any kind of character encoding on either side, should I be when using raw image data?
You can use DataInputStream to read the byte stream.
URL url = new URL("http://i.stack.imgur.com/ILTQq.png");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
DataInputStream dis = new DataInputStream(conn.getInputStream());
FileOutputStream fw = new FileOutputStream(new File("/tmp/img.png"));
byte buffer[] = new byte[1024];
int offset = 0;
int bytes;
while ((bytes = dis.read(buffer, offset, buffer.length)) > 0) {
fw.write(buffer, 0, bytes);
}
fw.close();
Alternatively an instance of BufferedImage can be created directly from the URL using ImageIO.read(java.net.URL).
URL url = new URL("http://i.stack.imgur.com/ILTQq.png");
BufferedImage image = ImageIO.read(url);
My goal is to upload a file from an action to a servlet.
Till now, I thought I had it working in this way:
Action: reads file as bytearray, converts it into String and puts String on request
HttpURLConnection conn =null;
String url = "http://myServlet");
URL obj = new URL(url);
conn = (HttpURLConnection) obj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("GET");
StringBuffer requestParams = new StringBuffer();
requestParams.append("fileString");
requestParams.append("=").append(URLEncoder.encode(fileString, "ISO-8859-1"));
//Append more params
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(requestParams.toString());
wr.flush();
conn.getContentLength();
Servlet: get String parameter, converts it back to bytearray and re-creates the file
receivedString = request.getParameter("fileString");
//Convert to bytearray and create file
But I guess this isn't a good solution, cause sometimes the call just fails because of the string (length maybe?)
Which is the right way to send my file? I can't find a way to send the file AND additional informations putting them on the request.
servelt code
System.out.println(" ================servlet==================");
InputStream in = request.getInputStream();
int a = in.available();
byte[] b = new byte[a];
in.read(b);
String stringValue = new String(b,"utf-8");
System.out.println("receive data==="+stringValue);
OutputStream dataOut = response.getOutputStream();
String responseData = "<test>test</test>";
System.out.println("response datea==="+responseData);
dataOut.write(responseData.getBytes("utf-8"));
dataOut.flush();
dataOut.close();
client code
System.out.println("================client======================");
java.net.URL url = new java.net.URL("test address");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
String sendData = "<data>send</data>";
System.out.println("send data="+sendData);
OutputStream dataOut = con.getOutputStream();
dataOut.write(sendData.getBytes("utf-8"));
dataOut.flush();
dataOut.close();
InputStream in = con.getInputStream();
int a = in.available();
byte[] b = new byte[a];
in.read(b);
String stringValue = new String(b,"utf-8");
in.close();
System.out.println("receive data="+stringValue);
I get the print results
servlet console
================servlet==================
receive data===
response datea===test
client console
================client======================
send data=<data>send</data>
receive data=<test>test</test>
My question is that servlet can't receive the data from the client
who can help me?
My question is that servlet can't receive the data from the client
It may not be the only problem, but this code is completely broken:
int a = in.available();
byte[] b = new byte[a];
in.read(b);
You're assuming that all the data is available right at the start. You should instead be reading from the stream until it runs out of data. Given that you want the result as text, I'd wrap the stream in an InputStreamReader and read from there. For example:
BufferdReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println("Servlet read line: " + line);
}
If you actually want to read it as XML, you should be able to pass the InputStream (or Reader) to an XML parser library to create a DOM.
You should be doing the same thing in the client code too, by the way. Basically:
Never ignore the return value of InputStream.read
Avoid using available(); it's rarely appropriate
Use an InputStreamReader to read text from a stream, rather than constructing it yourself from the bytes
Use an XML API to read XML rather than handling it as raw text
As of now I can see that the value of int b is 0 so it is not reading any data from the input stream.
According to this documentation
available
will always return 0 for InputStream which has been extended byt the
ServletInputStream.
As told by Jon or
Edit:
InputStream is=request.getInputStream();
OutputStream os=response.getOutputStream();
byte[] buf = new byte[1024];
int chunk = is.read(buf);
I'm downloading a picture on a android device from a SQL database; Everything works well, except that opening the Stream takes very long time (even if there is no picture to download). It takes approx 5 sec's before the actual download starts. Here is my code snippet:
URL url = new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
//input = connection.getInputStream();
InputStream input = new BufferedInputStream(url.openStream());
File file = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyCameraApp" + "/testpic.jpg");
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
//---blabla progressbar update etc..
The line InputStream input = new BufferedInputStream(url.openStream()); gives the problem. Any idea's on how to speed things up?
That's the point at which the actual TCP connection is created. It's a network problem, not a coding problem. Nothing you can do in the code to fix it.
I use this code to get a bitmap from a url. :)
Bitmap bitmap = null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
try
{
byte[] bytes=new byte[1024];
for(;;)
{
int count=is.read(bytes, 0, 1024);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
os.close();
bitmap = decodeFile(f);
You're calling url.openStream() when creating the InputStream, but prior to that you're creating a new connection and calling connection.connect().
From the android JavaDoc: openStream() is "Equivalent to openConnection().getInputStream(types)"
http://developer.android.com/reference/java/net/URL.html#openStream()
In summary I think you should call connection.getInputStream() when initialising the InputStream.