Android HttpUrlConnection passing header params - java

I searched other topics and there were some answers but I didn't succeed to solve my problem.
I have this code and I want to add "Referer" to my http headers.
After using setRequestProperty method, I log the results in Logcat but I don't see referer in the output. what am I doing wrong?
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Referer", "http://www.example.com");
for(int i=0;con.getHeaderFieldKey(i)!=null;i++){
String headerName = con.getHeaderFieldKey(i);
String headerValue = con.getHeaderField(i);
Log.d("Header", headerName + ": " + headerValue);
}
I also have another code which is not working either:
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
String IRNIC = cookies.get("IRNIC");
String ROUTEID = cookies.get("ROUTEID");
String myCookies = "IRNIC="+IRNIC+"; ROUTEID="+ROUTEID;
con.setRequestProperty("Cookie", myCookies);
for(int i=0;con.getHeaderFieldKey(i)!=null;i++){
String headerName = con.getHeaderFieldKey(i);
String headerValue = con.getHeaderField(i);
Log.d("Header", headerName + ": " + headerValue);
}
For the first code, I don't see referer in the output and also for the second code, I don't see cookies too.
So it seems setRequestProperty is not working!
Thanks in advance.
EDIT: I can see headers in the output but not the ones I added via setRequestProperty method. so the if code is working.

From docs:
getHeaderFields
Returns an unmodifiable map of the response-header fields and values
setRequestProperty
Sets the value of the specified request header field.
Request is not the same as response. That's why your headers are different. The request will have correct headers using setRequestProperty

Related

How do i fetch the custom headers in java which is set in node js or sent by nodejs

Frontend pass the request to nodejs application and nodejs pass the request call to JAVA.
I am using following code to authenticate my REST apis and make connection to the specified url.
I want to add or print the custom headers passed in request.
public HttpURLConnection establishConnection(String baseurl, String methodtype, String userId,
HttpHeaders headers) {
URL url;
JSONObject userInfo=new JSONObject();
try {
url = new URL(baseurl);
output = "";
userInfo=getUserName(headers.getHeaderString(HttpHeaders.AUTHORIZATION));
String userpass=null;
if (userId.isEmpty())
userpass = userInfo.getString("username") + ":" + userInfo.getString("password");
else
userpass = userId + ":" + userInfo.getString("password");
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization",basicAuth);
conn.setRequestMethod(methodtype);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json");
conn.setConnectTimeout(60000); // 60 seconds
conn.setDoOutput(true);
return conn;
}
}
How do i fetch the custom headers passed in request ? Which method should i use ? or Class that i can use to fetch the custom headers.
using #HeaderParam("customparamname") String param , with this param #HeaderParam i m able to get custom parameter value.

how to get odata.nextlink from the returned json object in java and call the odata.nextlink url

Currently I'm using
HttpSession session = (HttpSession) request.getSession();
AuthenticationResult result = (AuthenticationResult) session.getAttribute(AuthHelper.PRINCIPAL_SESSION_NAME);
String accessToken = result.getAccessToken();
String tenant = session.getServletContext().getInitParameter("tenant");
url = new URL("https://graph.windows.net/" + tenant + "/users/" + result.getUserInfo().getUniqueId()
+ "/memberOf?api-version=1.6");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// Set the appropriate header fields in the request header.
con.setRequestMethod("GET");
con.setRequestProperty("api-version", "1.6");
con.setRequestProperty("Authorization", "Bearer " + accessToken);
con.setRequestProperty("Accept", "application/json;odata=minimalmetadata");
jsonResponse = HttpClientHelper.getResponseStringFromConn(con, true);
which returns the groups which the user belongs to. It is limited to 100 and I'm getting the odata.nextlink. I currently don't know how to use that and recall the graph api to fetch the next set of 100
Please help!!
Or is there any way to increase the limit of response to be greater than 100?
Usually, the odata.nextlink would show like : directoryObjects/$/Microsoft.DirectoryServices.User/b202e3e2-ead2-4878-8f77-81889ce30989/memberOf?$skiptoken=X'445370740900010000000000000000140000005948A9EA0D7571449DAAEF76844271C101000000000000000000000000000017312E322E3834302E3131333535362E312E342E32333331020000000000018020591539727941B538A64692E459E9'
Then, you just need to generate a new request url as: new URL("https://graph.windows.net/" + tenant + "/" +odata.netlink + "&api-version=1.6");
Then, just make another request with Authorization header.
Thanks.

Jira Cloud JWT Generation 401 error

I was trying to make Jira cloud rest api call using JWT authentication.
I've followed the steps found in atlassian documentation but I've got this exception:
com.atlassian.jwt.exception.JwtInvalidClaimException: Expecting claim 'qsh' to have value 'qsh value' but instead it has the value 'qsh value'
Thanks in advance
Here is the answer
//1-First we need to create the qsh 'Query String Hash'
String httpMethod = "GET";
String restApiPath = "rest api url without the base url";
String urlParameters = "key=value&key1=value1";
String qsh = String.format("%s%s%s%s%s", httpMethod, "&", restApiPath, "&", urlParameters);
//2-Encode qsh
String encodedQsh = JwtUtil.computeSha256Hash(qsh);
//3-Create JwtJsonBuilder
JwtJsonBuilder jwtJsonBuilder = new JsonSmartJwtJsonBuilder();
jwtJsonBuilder.issuedAt(issuedAt);
jwtJsonBuilder.expirationTime(expiresAt);
jwtJsonBuilder.issuer(issuer);
jwtJsonBuilder.subject(subject);
jwtJsonBuilder.type("JWT");
jwtJsonBuilder.queryHash(encodedQsh);
//4-Encode JWT token
String encodedJwt = new NimbusJwtWriterFactory().macSigningWriter(SigningAlgorithm.HS256, "shared-secret- value").jsonToJwt(jwtJsonBuilder.build());
//5-Build your URL
String urlStrg = baseUrl + restApiPath + "?" + urlParameters
//6-Open Url Connection
URL url = new URL(urlStrg);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Accept", "application/json");
httpURLConnection.setRequestProperty("Authorization", "JWT " + encodedJwtToken);
httpURLConnection.setRequestMethod(httpMethod);
int responseCode = httpURLConnection.getResponseCode();
//responseCode to check if the request is valid and authenticated

How can I browse web site after login using https/http protocol(in Java)

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()

getting 505 responce from server

Hi in my android project i m calling a webservice and sending get parameter through query string parameter , now problem is that if query string parameter value contains any white space then i am getting 505 error
URL url = new URL(urlstring.trim());
urlConnection = (HttpURLConnection) url.openConnection();
int response = urlConnection.getResponseCode();
I have one doubt if i use URLEncode(urlstring.trim(),"UTF-8")do i need to change my webservice code also ?
You should encode only the values of your params:
String urlString = "http://test.com?param1=" + URLEncoder.encode(value1, "UTF-8") + "&param2=" + URLEncoder.encode(value2, "UTF-8") ;
URL url = new URL(urlstring.trim());
urlConnection = (HttpURLConnection) url.openConnection();
int response = urlConnection.getResponseCode();

Categories

Resources