I'm trying to use HttpURLConnection to send and receive messages in an Android application. This code works fine in a java application, but when running on Android I get the following exception:
java.lang.ClassCastException: com.android.okio.RealBufferedSink$1 cannot be cast to java.io.ByteArrayOutputStream
The code where this occurs:
URL url = new URL(destURI.toString());
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// Set request properties and headers
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty(HEADER_CONTENT_TYPE, CONTENT_TYPE_LS);
con.setRequestProperty(HEADER_CONTENT_LENGTH, new Integer(wrapperBytes.length).toString());
con.setRequestMethod(METHOD_POST);
// Set connect and read timeouts
con.setConnectTimeout(timeoutInMillis);
con.setReadTimeout(timeoutInMillis);
// Write request content
ByteArrayOutputStream out = (ByteArrayOutputStream) con.getOutputStream();
out.write(wrapperBytes);
out.flush();
I've looked at the android reference pages and these seem to say what I'd expect, getOutputStream() returns an OutputStream. This should then be able to be cast to a ByteArrayOutputStream.
Where is the RealBufferedSink coming from? Why am I not getting an OutputStream back?
Any help would be greatly appreciated!
Casting
ByteArrayOutputStream out = (ByteArrayOutputStream) con.getOutputStream();
is not recommended,
you might try:
OutputStream out = new BufferedOutputStream(con.getOutputStream());
Related
I'm trying to send a jsonObject to a web server using POST request method with android studio. In some cases it works fine, but in others I get this error:
Method threw 'java.lang.StackOverflowError' exception. Cannot evaluate org.json.JSONObject.toString()
If I reduce the JSON size it works fine.
This is how I'm doing it:
URL url;
HttpURLConnection connection = null;
url = new URL("MYURL");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
OutputStream outputStream = new BufferedOutputStream(connection.getOutputStream());
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
bufferedWriter.write("idUser=" + idUser + "&myJsonArray=" + finalobjectCopy + "&act=backupDados_V2&data=" + currentDateandTime);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
connection.connect();
(I can't upload my JSON)
According to this website my JSON is ok
How can I fix this and what doase this error mean?
Edit:
If I try to send the JSON using Insomnia it works fine. So the problem is on the android side.
Edit_2:
After several attempts, I found that the problem is in the text I am trying to pass as JSON.
The text was copied by a user from a web page and must have something blocking the correct formation of the JSON.
I have alleready tryed this:
myString = myString.replaceAll("[^\\x00-\\x7F]", "");
// erases all the ASCII control characters
myString = myString.replaceAll("[\\p{Cntrl}&&[^\r\n\t]]", "");
But the problem is the same. I am 95% sure the problem is the text that was copied. Is there any way to get around this situation?
The copied text is from this page:
http://www.aquarismopaulista.com/hemigrammus-erythrozonus/
I am using an Android app to send a base64 encoded string to a CherryPy server. The Android code works like this:
URL url = new URL("http://foo.bar/blabla");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "application/octet-stream");
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(base64s.length());
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
out.write(base64s.getBytes());
So, you'd say the amount of bytes sent equals the amount of bytes in the Content-Length header. However, in Python, when I run this:
cl = cherrypy.request.headers['Content-Length']
rawbody = cherrypy.request.body.read()
print "{} bytes, {}".format(len(rawbody), cl)
The numbers cl and len(rawbody) are different.
How can that be?
Maybe you forgot to close the stream with out.close(); ?
your server sould send a "close header" so the client will no its end stream for him.
The below code simply is not working on my Android Galaxy Nexus running v4.0.2 it works in the emulator and other older devices. When running on older devices and the emu the variable "is" is getting all the bytes as needed and all is good. While running on the Nexus it throws the file not found exception at "is" and "is" stays null. Then when I try to work with "is" further down the class it throws a null pointer because "is" is null. How can I fix this file not found error? The file is reachable on other devices/emu/browser.
I am getting java.io.FileNotFoundException: at is = urlConnection.getInputStream();
Here is the code:
// GET
InputStream is = null;
try {
// set the URL that points to a file to be downloaded
URL url = new URL(downloadURL);
// create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
// set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
// connect and download
urlConnection.connect();
// used in reading the data from the internet
is = urlConnection.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
urlConnection.setDoOutput(true);
Should be:
urlConnection.setDoOutput(false);
urlConnection.setDoOutput(true) effectively changes the method to POST, so probably your server doesn't respond to POST?
HTTPUrlConnection has an ugly and confusing interface indeed. Here's a recent writeup on its peculiarities:
http://www.tbray.org/ongoing/When/201x/2012/01/17/HttpURLConnection
I am able to do a POST of a parameters string. I use the following code:
String parameters = "firstname=john&lastname=doe";
URL url = new URL("http://www.mywebsite.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(parameters);
out.flush();
out.close();
connection.disconnect();
However, I need to do a POST of binary data (which is in form of byte[]).
Not sure how to change the above code to implement it.
Could anyone please help me with this?
Take a look here
Sending POST data in Android
But use ByteArrayEntity.
byte[] content = ...
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new ByteArrayEntity(content));
HttpResponse response = httpClient.execute(httpPost);
You could base-64 encode your data first. Take a look at the aptly named Base64 class.
These links might be helpful:
Android httpclient file upload data corruption and timeout issues
http://getablogger.blogspot.com/2008/01/android-how-to-post-file-to-php-server.html
http://forum.springsource.org/showthread.php?108546-How-do-I-post-a-byte-array
I have simple code :
URL url;
BufferedReader in = null;
HttpURLConnection connection;
InputStream is = null;
InputStreamReader br = null;
setProgressTitle(progress, context.getString(R.string.loading));
setProgressMessage(progress, context.getString(R.string.loading_from_internet));
try {
url = new URL(urlStr);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(Const.TIMEOUT);
is = connection.getInputStream();
...
If I have urlStr = "http://samlib.ru/w/waliduda_a_a/molochnischituran1.shtml" - all is work fine.
If I use urls like urlStr = "http://samlib.ru/cgi-bin/areader?q=jlist" - I got a error in connection.getInputStream();
**
03-04 15:37:52.459: ERROR/DataReader::loadDataFromInet(17281): Failed loading http://samlib.ru/cgi-bin/areader?q=jlist
03-04 15:37:52.459: ERROR/DataReader::loadDataFromInet(17281): java.io.FileNotFoundException: http://samlib.ru/cgi-bin/areader?q=jlist
03-04 15:37:52.459: ERROR/DataReader::loadDataFromInet(17281): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:521)
**
How can I upload data to a similar url?
There are a couple of reasons this might happen. Where I've personally seen it is when I've put in a URL that was subsequently redirected, HttpURLConnection doesn't handle that. I got the same response as you, I hit it with FF and it works fine. Its also possible that some sort of browser sniffing might be done on the recieving side.
Good Luck!
It looks like your cgi-bin/areader is not found. Getting an HTTP/404 response code:
wget http://samlib.ru/cgi-bin/areader?q=jlist
--2011-03-04 09:03:17-- http://samlib.ru/cgi-bin/areader?q=jlist
Resolving samlib.ru... 81.176.66.171
Connecting to samlib.ru|81.176.66.171|:80... connected.
HTTP request sent, awaiting response... 404 Not Found
2011-03-04 09:03:17 ERROR 404: Not Found.
Correct that then try again.