how to get the client port of a URLConnection in java - java

Is it possible to get the client side port number of a URLConnection in java, I didn't find any method to do that.
edit:
I am on client side. As java API said, it will try to use the same connection for any URL, just like set "keep-alive" to true. And I want to verify this by:
1: create a URL by using new URL(someurl)
2: create a second URL by using new URL(someurl), the same ulr
3: get the client port for both 1 and 2. If they are the same, then there should be the same connection, meaning java reuse the connect as setting keep-alive.

there is no such method in java.

Is it possible to get the client side port number of a URLConnection
in java
No, it is not possible and there is no method through which you can get that.

Related

can I send same HTTP request with same HttpURLConnection multiple times?

In order to send a string data to the server once, I do as below:
Make “HttpURLConnection” to my URL address and open it
Set the required headers
for the connection I Set setDoOutput to True
new a DataOutputStream from my connection and finally write my string data to it.
HttpURLConnection myConn = (HttpURLConnection);
myUrl.openConnection();
myConn.setRequestProperty("Accept", "application/json, text/plain, */*");
myConn.setDoOutput(true);
DataOutputStream my_output = new DataOutputStream(myConn.getOutputStream());
my_output.write(myData.getBytes("UTF-8"));
But what to do if I want to send exactly the same data with same URl and headers multiple times?
Can I write to it multiple times?(I mean that is it possible to use the last line of code multiple times?) Or should I repeat the above steps and try it with a new connection?
And if yes should I wait for some second or millisecond before sending the next one?
I also searched for some other alternatives such as “HttpClient” Http API and making synchronous Http request which as far as I got can help me setting the headers only once.
At the end, I appreciate your help and support and any other alternatives would be welcome.
Thanks a million.
I understand that the question has be answered in the comments, but I am leaving this here so that future viewers can see it.
An HTTP request contains 3 main parts:
Request Line: Method, Path, Protocol
Headers: Key-Pairs
Body: Data
Running my_output.write() will just add bytes to the body until my_output.flush() has been executed. Flushing the stream will write the data to the server.
Because HTTP requests are usually closed by the server once all data has been sent/received, whether or not you create a new connection or just add on to the body depends on your intentions. Typically, clients will create a new connection for each request because each response should be handled individually, rather than sending a repetitive body. This will vary though because some servers choose to hold a connection (such as WebSockets).
If you are open to external libraries, you may find this chart insightful:
AsyncHttpClient would be a good fit for your intentions.
Alternatively, you can use cURL by running a terminal command with Runtime.getRuntime().exec(). More information about using cURL with POST Requests can be found here. While cURL is efficient, you have to depend on the fact that your OS supports the command (though usually all devices that can run Java have this command).

java.security.cert.CertificateException: No subject alternative names matching IP address

I have different issues with this exception, Please try to understand.
I'm sending data from one application to another through web service call in Java.
whenever I called it will connect to some other application. in that
a situation I get the above exception, this problem occur only in
byte Grid server.
We solved above problem like this our admin removed security,
means we have https they removed s so we are working with
HTTP, but it's not good, I want to connect through web service call with security, can any one give me the best idea.Please see my sample code
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
String request = PropertyFactory.getProperty("someUrl");
url = new URL(request);
postConnection = (HttpURLConnection) url.openConnection();
can I handle through code?
If you are using Oracle JDK between 1.8.0_51 and 1.8.0_60, there was an issue when connecting via IP address instead of hostname. In the case of using the IP-address, this address also has to be mentioned in the Subject alternative names of the cert. According to Mulesoft Support a workaround would be to set the JVM argument "jdk.tls.trustNameService" to true - resulting in a reverse name lookup for the IP address.
Byte grid having internal firewall so its may be stop, Please contact with byte grid team.

HTTPS Post request (not) using certificate/hash print?

I admit there is a possibility that I am not well informed about the subject, but I've done a LOADS of reading and I still can't get answer to my question.
From what I have learnt, to make communication secure with HTTPS I need to be using some sort of public key (reminds me of pgp-encryption).
My goal is to make a secured POST request from my java application (which I, in the moment it starts working, will rewrite to Android app, if it matters) to a php application accessible via https address.
Naturally I did some Google research on the topic and I got a lot of results how to make ssl connection. Non of those results used any sort of certificate/hash prints. They just use HttpsURLConnection instead of HttpURLConnection, everything else is almost identical.
Right now, almost copy paste of something I found here is this:
String httpsURL = "https://xx.yyyy.zzz/requestHandler.php?getParam1=value1&getParam2=value2";
String query = "email=" + URLEncoder.encode("abc#xyz.com", "UTF-8");
query+="&";
query+="password="+URLEncoder.encode("tramtarie","UTF-8");
URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-length",String.valueOf(query.length()));
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 5.0;Windows98;DigExt)");
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(query);
output.close();
DataInputStream input = new DataInputStream(con.getInputStream());
for(
int c = input.read();
c!=-1;c=input.read())
System.out.print((char)c);
input.close();
System.out.println("Resp Code:"+con.getResponseCode());
System.out.println("Resp Message:"+con.getResponseMessage());
Which sadly does not work and ends up with this exception:
Exception in thread "main" javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative DNS name matching app.elessy.cz found
This probably means that it checks the certificate and finds out that the certificate I am using does not match domain name for which is registered (it is webhosting certificate, registered for webhosting domain, not the domain I own, the only reason I am using https is to secure data for internal purposes, I do not want this site to be visited by users from outside, so this certificate should be ok).
There are two things that I just don't get about the code and everything.
No code I have been able to find use MD5/SHA-1 (supposedly the public keys for message encryption?) prints or
certificate, they just somehow automatically connect to https
website and should work. Doesn't work for me though.
Do I really need those md5/sha-1 prints that are provided to me? Or at least, what in the given context do those prints mean?
Edit:
Following the given answer and duplicate mark, I managed to get it working - in the meaning that I can communicate with application behind https.
But I didnt have to use any sort of md5/sha1 print. How do I know now that it is safe? Does this protocol on his own? Like that communication is secured either way, when I use built-in java classes to connect to app behind https?
I probably do not seek for precise technical explanation, but more for an assurance that yes - the communication is safe even though I do not use (knowingly) certificate/servers public key to encrypt my messages. That it does the ssl connection for me.

Java: handling webcal protocol

I'm trying to download - or even just open a stream - to a calendar located at webcal://www.somewhere.com/foo?etc=bar.
The Java URL class is throwing a "unknown protocol: webcal" exception when I do:
URL url = new URL("webcal://...");
How can I tell the URL class that it should just use HTTP as trasport protocol even if the web resource is located somewhere behind a webcal:// protocol?
Or, in any case, how can I get my calendar downloaded?
Please, bear in mind that the web server I'm calling does not serve the calendar if I try to replace the "webcal://" with "http://".
As far as I understand, Apple's use of "webcal" really is just a synonym for "http"; so it's supposed to work.
The "webcal://" is an unofficial URI scheme, see Wikipedia article on it.
As such it might stand for one or another back end implementation - e.g. the web server you are calling might be using any of the mentioned protocol implementations, such as WebDAV, CalDAV or OpenDAV
However if all you want is to read the contents of the file, then any HTTP client should do the trick, because the above mentioned protocols are based on HTTP.
Here is an example on how to read a remote iCal using URL's own mechanism for opening HttpURLConnection :
URL calendarURL = new URL("http://www.facebook.com/ical/b.php?uid=myUID&key=myKEY");
URLConnection connection = calendarURL.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while (reader.ready()) {
System.out.println(reader.readLine());
}
As you can see I have changed the original URL from
webcal://www.facebook.com/ical/b.php?uid=MYUID&key=MYKEY
to
http://www.facebook.com/ical/b.php?uid=MYUID&key=MYKEY
, because we use a java.net.URL and by default Java does not recognize this protocol. If indeed the web server you want to contact only serves the content over webcal:// then you might need to use the appropriate client (based on the exact protocol implementation the server uses). For example there are a multitude of frameworks that provide WebDAV client capabilities, such as JackRabbit, Sardine, etc.
If you provide more information on the type of server we can dig further.

Jsoup error 502

I'm trying to use jsoup to login to a website (intranet page with some subsystems), enter in a subsystem, search something and parse the page.
I can login, but when I try to access the subsystem I receive an HTTP error 502. However in the browser opens normally.
I think that is some problem with a proxy (which is already set in java). After some few tries my login is blocked and I get the HTTP error 407 (page blocked or something like that)
I already tried to put .useragent("mozilla..."), .timeout(...), .ignorehttperrors(true), ignorecontenttype(true) and using .cookie too.
Is there some way to solve this?
Response x = Jsoup.connect("page").data("...").method(method.GET).execute();
I used the given suggestion (apache httpclient and I don't get the HTTP errors anymore.
But I still want to know if jsoup can bypass this problem, because I could use just one .jar instead 6 (5 from apache plus jsoup to parse the responses.). Thanks to those that who edited my post (rs) and to ollo for the suggestion.
Here's an example using Java's UrlConnection:
URLConnection connection = new URL("your url").openConnection();
connection.addRequestProperty("http.proxyHost", "proxy server");
connection.addRequestProperty("http.proxyPort", "proxy port");
// Alternative:
System.setProperty("http.proxyHost", "yourproxyserver");
System.setProperty("http.proxyPort", "portnumber");
InputStream responseStream = connection.getInputStream();
// Read response into buffer and parse it with jsoup
See also my answer here: JSoup over VPN/proxy
(i guess thats a better one)
But i realy reccommend you HttpClient (or a similar one) for such connection things. As i said before, jsoup as only a limited connection support.

Categories

Resources