I am trying use the HTTPURLConnection class to open connection to a JSP and receive a response from a servlet. A response header is set in the JSP that need to be read in the servlet.
The code sample is as below
String strURL = "http://<host>:<port>/<context>/mypage.jsp";
String sCookies = getCookie();//method to get the authentication cookie(**SSOAUTH**) and its value for the current logged in user
URL url = new URL(strURL);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestProperty("Cookie", URLEncoder.encode(sCookies, "UTF-8"));
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
DataOutputStream out = new DataOutputStream(urlConnection.getOutputStream());
out.writeBytes("lang=en");
out.flush();
out.close();
//reading the response received from JSP and retrieve header value
response.write(urlConnection.getHeaderField("commAuth") + "<br />");
The issue is the passed SSOAUTH cookie is not sent to the JSP. If I send the UID/PWD instead of cookie as below the authentication succeeds and response is sent correctly.
urlConnection.setRequestProperty("username", "testuser");
urlConnection.setRequestProperty("password", "testpwd");
Is this the right way of sending cookie over HTTPURLConnection? or are there other parameters that need to be set?
You may want to try removing the URLEncoder.encode from the entire sCookies String. The cookie format should be in the form of NAME=VALUE, but by URLEncoding the whole string you will escape the =.
Related
For Card Payment Authorization, we are passing the Customer details and Card details as part of request.
I want to see these how these information will appear/processed in the Authorization.Net
Below is the code snippet
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
String requestString="x_login=abcd&x_tran_key=***&x_version=**&x_first_name=test&x_last_name=test&x_card_num=0000&x_exp_date=10/2022&x_card_code=000";
// Post the data in the string buffer
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.write(requestString.getBytes());
out.flush();
out.close();
// gateway response
connection.getInputStream();
From this I want to know how they differentiating the param and how this payload appears to them.
I am trying to send HTTP PUT request to Cloudant database to update a key "BPInc" to "N". Its current value is "Y". I am using HTTPURLConnection to make the connection and send request. I am able to send GET request successfully and retrieve the BPInc value. But when I am sending the PUT request, I am getting error code - 400.
I have also looked into cloudant-client library, but not able to get how to send PUT request and I want to stick to HTTPURLConnection method only.
Here's the code ,
// After retrieving _rev and _id using GET request......
String revID = "_rev of the document";
String docID = "_id of the document";
URL postUrl = new URL("<Cloudant URL>/<DB NAME>/" + docID);
String usernameColonPassword = "<API KEY>:<PASSWORD>";
String basicAuthPayload = "Basic " + Base64.getEncoder().encodeToString(usernameColonPassword.getBytes());
HttpURLConnection conn = (HttpURLConnection)postUrl.openConnection();
conn.setRequestMethod("PUT");
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Authorization", basicAuthPayload);
conn.setDoOutput(true);
OutputStreamWriter json = new OutputStreamWriter(conn.getOutputStream());
json.write(String.format("{\"_rev\":revID, \"BPInc\":\"Y\"}"));
json.flush();
json.close();
int putResponseCode = conn.getResponseCode();
I am very new to this so I suppose I might be doing wrong something. Please suggest.
I want to read the content of a text file which is located in the site
https://www.frbservices.org/EPaymentsDirectory/FedACHdir.txt
I want to read it using Java . I started it with using HttpsUrlConnection Class .
When we take the above URL in the browser , we will first redirect to a agreement page and if we click the agree button , we can see the text file . How we can do the same procedure using HttpsUrlConnection class ?
This is what I tried:
URL url = new URL("https://www.frbservices.org/EPaymentsDirectory/submitAgreement?agreementValue=Agree");
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setRequestMethod("POST");
https.connect();
url = new URL("https://www.frbservices.org/EPaymentsDirectory/FedACHdir.txt");
HttpsURLConnection http = (HttpsURLConnection) url.openConnection();
http.setRequestMethod("GET");
http.connect();
String line = "";
BufferedReader in = new BufferedReader( new InputStreamReader(http.getInputStream()));
while( (line = in.readLine()) != null )
{System.out.println(line);
//process line
logger.debug(line);
processLine(line);
}
http.disconnect();
Any inputs will be highly appreciable
Looks like the POST request to accept the agreement results in a session cookie from the server which likely stores whether or not the agreement is accepted. You could try getting the JSESSIONID cookie from the "Set-Cookie" header and sending it in your "Cookie" header to simulate the behaviour of the browser.
I'm trying to login web site using Java and I succeeded. Below is the code I used.
String query = "myquery";
URL url = new URL(loginUrl);
HttpsURLConnection con = (HttpsURLConnection) url.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 );
// this page returns JavaScript code
}
After this, I want to access another web page in same domain, so I tried below code.
URL url = new URL(anotherUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
... similar to above code ...
But this page asks me to login again. I think connection has been disconnected in the process of changing URL. (Onlt login page uses HTTPS protocol and other pages use HTTP protocol)
How can I fix this?
Someone please help
Keep in mind that HTTP is completely stateless. The idea of "logging in" to a site translates to (usually) setting cookies from an HTTP perspective. Those cookies are simply HTTP headers and they are sent with each subsequent request by your browser. So for you to maintain the logged in state its up to you get the cookies from the response headers and send them along with future requests.
Here is how:
Retrieving cookies from a response:
Open a java.net.URLConnection to the server:
URL myUrl = new URL("http://www.hccp.org/cookieTest.jsp");
URLConnection urlConn = myUrl.openConnection();
urlConn.connect();
Loop through response headers looking for cookies:
Since a server may set multiple cookies in a single request, we will need to loop through the response headers, looking for all headers named "Set-Cookie".
String headerName=null;
for (int i=1; (headerName = uc.getHeaderFieldKey(i))!=null; i++) {
if (headerName.equals("Set-Cookie")) {
String cookie = urlConn.getHeaderField(i);
...
Extract cookie name and value from cookie string:
The string returned by the getHeaderField(int index) method is a series of name=value separated by semi-colons (;). The first name/value pairing is actual data string we are interested in (i.e. "sessionId=0949eeee22222rtg" or "userId=igbrown"), the subsequent name/value pairings are meta-information that we would use to manage the storage of the cookie (when it expires, etc.).
cookie = cookie.substring(0, cookie.indexOf(";"));
String cookieName = cookie.substring(0, cookie.indexOf("="));
String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length());
This is basically it. We now have the cookie name (cookieName) and the cookie value (cookieValue).
Setting a cookie value in a request:
Values must be set prior to calling the connect method:
URL myUrl = new URL("http://www.hccp.org/cookieTest.jsp");
URLConnection urlConn = myUrl.openConnection();
Create a cookie string:
String myCookie = "userId=igbrown";
Add the cookie to a request:
Using the
setRequestProperty(String name, String value);
method, we will add a property named "Cookie", passing the cookie string created in the previous step as the property value.
urlConn.setRequestProperty("Cookie", myCookie);
Send the cookie to the server:
To send the cookie, simply call connect() on the URLConnection for which we have added the cookie property:
urlConn.connect()
I am newbie developer in Java. STEP 1 I have already done the the following:
Logged in to REST API server (with login&password)
Received a token in XML format which i parsed with SAX parser so now i
am in a position of a token. Below is the sample code for Login:
Java code:
String url1 = "https://api4.liverail.com/login";
URL obj = new URL(url1);
HttpsURLConnection con1 = (HttpsURLConnection) obj.openConnection();
String urlParameters ="username=paania#gmail.com&password=d372a15b714bd250e";
con1.setDoOutput(true);
con1.setRequestMethod("POST");
DataOutputStream wr = new DataOutputStream(con1.getOutputStream());
wr.writeBytes(urlParameters);
STEP 2: I want to pass the token to REST API to obtain some information e.g a list from category but when i send the request via GET method , i get a response in XML saying [CDATA[You need to be logged in]] This is the code in Java:
String url = "http://api4.liverail.com/advertising/category/list/?token="72938howdwoi";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(newInputStreamReader(con.getInputStream()));
in.close();
con.disconnect();
I am not sure what i am missing here.
Any suggestions?
Just changed your url for request of data :
String url = "http://api4.liverail.com/advertising/category/list/?token=72938howdwoi";