I am trying to connect to a url with HttpUrlConnection. the host which user enter can be running on http:// or https://. when i am connecting it throws an exception as EOFException.
Is there any way that i identify that url is running on https through some error code or something ??
Following code i am using for this purpose.
HttpURLConnection.setFollowRedirects(true);
con = (HttpURLConnection) new URL(url[0]).openConnection();
con.setRequestMethod("POST");
con.setConnectTimeout(20000);
I m using the abode code what if the url is not valid like i type wwww.gooooooodldldle.com
which is not valid url. I am getting Java.net.SocketTimeout exception here
The URL cannot change after the connection has been created if you don't reacreate it again. I would do it like this to know the protocol.
URL url;
try {
url = new URL(url[0]);
if(url.getProtocol().equalsIgnoreCase(HTTPS){
Lod.i(TAG, "Is HTTPS connection");
} else {
Log.i(TAG, "Is HTTP connection");
}
} catch (EOFException eofEx) {
eofEx.printStackTrace();
}
After update:
You can check the url string with a Regular Expresion and then if it's correct try the connection. Or put all the logic inside a try catch and show a toast or dialog if the exception is rised.
Hope it helps.
If you won't mind, try to use android-async-http library instead
Related
I'm trying to access a local IP using an Android app with HttpURLConnection. The web server is working, I tested it with Postman. Using a microcontroller I can see when someone connects to that IP address, so I know it's something in my app that's not working.
I have the app set up so that it sends a POST request, and when I press the button the Android Studio profiler detects the request and shows the IP address, but it won't reach the microcontroller.
String urlString = "http://192.168.2.115/request"; // URL to call
OutputStream out = null;
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.connect();
} catch (Exception e) {
return e.getMessage();
}
I enabled the INTERNET and the ACCESS_NETWORK_STATE permissions in AndroidManifest.xml and am not yet sending or receiving any data, just trying to access the IP address
Any help is appreciated, thank you!
Edit: It works now, I needed to add conn.getInputStream(); after conn.connect, for whatever reason
In which thread do you try to make http connection? Android system is prohibit to make network connection on main thread. Probably should use AsyncTask/RxJava/Thread.
I have a url as following
String url = "http://host.com/connect/v1.3/serviceProducts?q=\"lookupName\" LIKE 'A9051%'"
This url points to a restful webservice. Whenever I try to hitting this url using HttpURLConnection but it always returns be 301 Moved Permanently response.
I have tried encoding the url. But still it failed to work. Below is the code of my attempt to encode it.
try {
url = URLEncoder.encode(url, "UTF-8");
} catch (UnsupportedEncodingException ex) {
java.util.logging.Logger.getLogger(DbInteraction.class.getName()).log(Level.SEVERE, null, ex);
}
url = url.replace("%3A", ":").replace("%2F", "/").replace("%3F", "?").replace("%3D", "=").replace("%25", "%");
After the encoding my url looks like this.
http://host.com/connect/v1.3/serviceProducts?q=%22lookupName%22+LIKE+%27A9051%%27
With this encoded url as well I'm still getting 301 Status.
I also tried with the below url format
http://host.com/connect/v1.3/serviceProducts?q=%22lookupName%22%20LIKE%20%27A9051%%27
I don't understand where am I going wrong. Please suggest.
I've tried testing the service in Postman and it works as expected there.
PS: This is a dummy url with modified host details.
UPDATE:
Here are some more ways I tried hitting the url:
http%3A%2F%2Fhost.com%2Fconnect%2Fv1.3%2FserviceProducts%3Fq%3D%22lookupName%22LIKE%27A9051%25%27
http://host.com/connect/v1.3/serviceProducts%3Fq%3D%22lookupName%22+LIKE+%27A9051%25%27
http://host.com/connect/v1.3/serviceProducts?q%3D%22lookupName%22+LIKE+%27A9051%25%27
http://host.com/connect/v1.3/serviceProducts?q=%22lookupName%22+LIKE+%27A9051%25%27
You should not do any replacements after you did URLEncoder.encode(url, "UTF-8"); because this is actually the encoded string that you need to use.
In my code, I need to connect one url say http://example.org . If the above url doesn't connect (connectivity issue or server down), I need to connect another url say http://example-1.org .
URL url = new URL("http://example.org");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
if (code != 200){
//try alternate url connection here.
}
Please suggest improved way to do my usecase.
Also in case the first url has not been connected for n times (or n minutes), then I need to connect the alternate url afterwards. I'll have property(will have value in DB) to set the connectivity of first url has failed. once the first url is up, then I manually change the value in DB to connect the first url.
Please help me.
I am trying to find a way to get the protocol from a URL that the user types in. I have an EditText set as uri in an android layout file. The user types in his web address as www.thiersite.com or theirsite.com.
Now how can I get the correct protocol from what they have typed in? It seems everywhere I look that you need to have either https:// or http:// as the protocol in the http request. I get a malformed exception when I don't have a protocol for their web address.
Is there a way to check the URL without having the need to have the protocol when they typed their address? So in essence, do I need to ask the User to type in the protocol as part of the URL? I would prefer to do it programmatically.
/**
* Protocol value could be http:// or https://
*/
boolean usesProtocol(String url,String protocol){
boolean uses = false;
try{
URL u = new URL( protocol.concat(url) );
URLConnection con = u.openConnection();
con.connect();
// the following line will be hit only if the
// supplied protocol is supported
uses = true;
}catch(MalformedURLException e){
// new URL() failed
// user has made a typing error
}catch(IOException e){
// openConnection() failed
// the supplied protocol is not supported
}finally{
return uses;
}
}
I believe that the code is self-explaining. The above code uses no external dependencies. If you do not mind using JSoup, there is another answer on SO that deals with the same: Java how to find out if a URL is http or https?
My Source: http://docs.oracle.com/javase/tutorial/networking/urls/connecting.html
I'm making a simple URL request with code like this:
URL url = new URL(webpage);
URLConnection urlConnection = url.openConnection();
InputStream is = urlConnection.getInputStream();
But on that last line, I'm getting the "redirected too many times error". If my "webpage" var is, say, google.com then it works fine, but when I try to use my servlet's URL then it fails. It seems I can adjust the number of times it follows the redirects (default is 20) with this:
System.setProperty("http.maxRedirects", "100");
But when I crank it up to, say, 100 it definitely takes longer to throw the error so I know it is trying. However, the URL to my servlet works fine in (any) browser and using the "persist" option in firebug it seems to only be redirecting once.
A bit more info on my servlet ... it is running in tomcat and fronted by apache using 'mod-proxy-ajp'. Also of note, it is using form authentication so any URL you enter should redirect you to the login page. As I said, this works correctly in all browsers, but for some reason the redirect isn't working with the URLConnection in Java 6.
Thanks for reading ... ideas?
It's apparently redirecting in an infinite loop because you don't maintain the user session. The session is usually backed by a cookie. You need to create a CookieManager before you use URLConnection.
// First set the default cookie manager.
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
// All the following subsequent URLConnections will use the same cookie manager.
URLConnection connection = new URL(url).openConnection();
// ...
connection = new URL(url).openConnection();
// ...
connection = new URL(url).openConnection();
// ...
See also:
Using java.net.URLConnection to fire and handle HTTP requests
Duse, I have add this lines:
java.net.CookieManager cm = new java.net.CookieManager();
java.net.CookieHandler.setDefault(cm);
See this example:
java.net.CookieManager cm = new java.net.CookieManager();
java.net.CookieHandler.setDefault(cm);
String buf="";
dk = new DAKABrowser(input.getText());
try {
URL url = new URL(dk.toURL(input.getText()));
DataInputStream dis = new DataInputStream(url.openStream());
String inputLine;
while ((inputLine = dis.readLine()) != null) {
buf+=inputLine;
output.append(inputLine+"\n");
}
dis.close();
}
catch (MalformedURLException me) {
System.out.println("MalformedURLException: " + me);
}
catch (IOException ioe) {
System.out.println("IOException: " + ioe);
}
titulo.setText(dk.getTitle(buf));
I was using Jenkins on Tomcat6 on a unix environment and got this bug. For some reason, upgrading to Java7 solved it. I'd be interested to know exactly why that fixed it.
I had faced the same problem and it took considerable amount of time to understand the problem.
So to summarize the problem was in mismatch of headers.
Consider below being my Resource
#GET
#Path("booksMasterData")
#Produces(Array(core.MediaType.APPLICATION_JSON))
def booksMasterData(#QueryParam("stockStatus") stockStatus : String): Response = {
// some logic here to get the books and send it back
}
And here is client code, which was trying to connect to my above resource
ClientResponse clientResponse = restClient.resource("http://localhost:8080/booksService").path("rest").path("catalogue").path("booksMasterData").accept("application/boks-master-data+json").get(ClientResponse.class);
And the error was coming on exactly above line.
What was the problem?
My Resource was using
"application/json"
in
#Produces annotation
and my client was using
accept("application/boks-master-data+json")
and this was the problem.
It took me long to find out this as the error was no where related. Break through was when I tried to access my resource in postman with
Accept-> "application/json" header
it worked fine, however with
Accept-> "application/boks-master-data+json" header
it doesnt.
And again, even Postman was not giving me proper error. The error was too generic. Please see the below image for reference.