I try to establisch a HttpsURLConnection with:
HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection()
but I get an Exception:
E/JavaBinder( 901): java.lang.ClassCastException: org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection
But I can't find out, why. The same example is everywhere across the web.
The ClassCastException is telling you that the object being returned is not a HttpsUrlConnection. The cast you are doing is inherently unsafe, instead you should something like:
URLConnection conn = new URL(url).openConnection();
if (conn instanceof HttpsURLConnection) {
// do stuff
}
else {
// error?
}
As to the reason its not giving you an Https version, what url are you providing it with? My guess is you are giving it http:.. instead of https:...
What is the URL? It looks like you are using a plain "http:" scheme URL, but expecting an HTTPS connection.
Related
I am trying to develop a part of my app in which i want to get video details for a keyword. I am using the search list API. I think I have an issue with the authorization. I am getting a 401. I have tried passing my authorization details.
I have tried the following code after going through a few resources online and I am current getting the java.io.FileNotFoundException at the line at which i get the Input Stream. The connection code that I am getting is a 401.
The given code is in the doInBackground of an AsyncTask.
String ytres="";
URL url;
HttpURLConnection urlConnection = null;
try {
Log.d("youtubedata","a1");
url = new URL("https://www.googleapis.com/youtube/v3/search?part=id&q=queen%20bohemian");
Log.d("youtubedata","a2");
Log.d("youtubedata","a");
urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty ("Authorization", "Bearer MYAPIKEY");
urlConnection.setRequestProperty ("Accept", "application/json");
Log.d("youtubedatanum",Integer.toString(urlConnection.getResponseCode()));
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
ytres=ytres+current;
System.out.print(current);
}
Log.d("youtubedata",ytres);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return ytres;
I do suspect the issue is in the way i have passed my API Key.
Please go through the API docs at Calling the API and at Search Endpoint.
You'll see that your URL does not contain the needed API key passed on as the key parameter.
It may also worth it to dug up Google's own sample Java implementation at Search.java. However, that code, due to the layer of library abstraction it uses, is not of immediate help since it obscures the way a client should work directly with the API.
For You-tube Data API error 401
Possible issue for unauthorized (401) can be
authorizationRequired
youtubeSignupRequired
Check You-tube Data API error doc Here.
Also confirm that you have follow THIS steps to integrate API.
Sample API Code you can find Here
Hope this can help you.
I am making a HttpUrlConnection with an Usgs API. This is my Url:
"https://earthquake.usgs.gov/fdsnws/event/1/queryformat=geojson&eventtype=earthquake&orderby=time&minmag=6&limit=10"
After thoroughly debugging, it seems that after connection.connect connection fails and jsonResponse is empty.
public static String makeHttprequest(URL url) throws IOException {
String jsonResponse = "";
HttpURLConnection connection = null;
InputStream stream = null;
try {
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(1000000);
connection.setConnectTimeout(1500000);
connection.connect();
stream = connection.getInputStream();
jsonResponse = readfromstream(stream);
} catch (IOException e) {
Log.e("IOException", "Error while making request");
}
return jsonResponse;
}
This is Log
Everything looks good. It seems to me that you have no internet connection in your running devices. Probably you are using emulator in your computer which is not connected to internet.
Please try to run in real device. It is working perfect for me.
A bit advice, please try to use libraries such as Retrofit or OkHttp. They are very much easier and handier than these old ways.
If you insist using HttpURLConnection, try the following
URL url = new URL(yourUrlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
Or for more formal use of HttpURLConnection, visit here. It shows several proper use of HttpURLConnection APIs.
https://developer.android.com/reference/java/net/HttpURLConnection
just tried my app on real device everything is working as expected there might be problem with emulator.
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());
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 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.