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") + "¶m2=" + URLEncoder.encode(value2, "UTF-8") ;
URL url = new URL(urlstring.trim());
urlConnection = (HttpURLConnection) url.openConnection();
int response = urlConnection.getResponseCode();
Related
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.
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 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
Doing GET request with URLConnection. code is here
java.net.URL url = new java.net.URL(requestUrl);
URLConnection urlConnection = url.openConnection();
is = new BufferedInputStream(urlConnection.getInputStream());
getting java.io.FileNotFoundException whereas requested url is correct. i think it may be https ssl certificate issue. if anyone else got this issue and resolved please update.
Encode your parameter to create an URL for request.Unsupported
character in parameter value may cause to exceptions it can be a white space also.
String url = "http://url.com";
String charset = "UTF-8"; // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
String param1 = "value1";
String param2 = "value2";
// ...
String query = String.format("param1=%s¶m2=%s",
URLEncoder.encode(param1, charset),
URLEncoder.encode(param2, charset));
URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
// ...
Courtsey
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