I am getting 400 response code with following code:
String authenticationUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
HttpsURLConnection authConn = (HttpsURLConnection) new URL(authenticationUrl).openConnection();
authConn.setRequestMethod("POST");
authConn.setDoOutput(true);
authConn.setRequestProperty("Ocp-Apim-Subscription-Key", key);
IOUtils.write("", authConn.getOutputStream(), "UTF-8");
String token = IOUtils.toString(authConn.getInputStream(), "UTF-8");
// Using the access token to build the appid for the request url
String appId = URLEncoder.encode("Bearer "+token, "UTF-8");
String[] languages = {"ar","bg","ca","zh","cs", "da","nl", "fi","fr","de","el","hu", "id", "it", "ja",
"ko","ms","no", "pl","pt","ro","ru", "es","sw","th","tr","uk","vi"};
US_LISTING_FULL_DESCRIPTION = URLEncoder.encode(readFile("d:\\desc1.txt", Charset.defaultCharset()), "UTF-8");
System.out.println("languages.length " + languages.length);
WrapperBean[] wrapperBean = new WrapperBean[languages.length];
try{
for (int i = 0; i < languages.length; i++) {
wrapperBean[i] = new WrapperBean();
wrapperBean[i].setLocale(languages[i]);
System.out.println("languages[i] " + languages[i]);
String url1 = String.format("https://api.microsofttranslator.com/v2/http.svc/Translate?appid=%s&text=%s&from=%s&to=%s", appId, US_LISTING_TITLE, "en", languages[i]);
HttpsURLConnection translateConn = (HttpsURLConnection) new URL(url1).openConnection();
translateConn.setRequestMethod("GET");
translateConn.setRequestProperty("Accept", "application/xml");
String translatetitle = IOUtils.toString(translateConn.getInputStream(), "UTF-8");
The last line in above code is where I get the error.
The exact error in Eclipse console is:
java.io.IOException: Server returned HTTP response code: 400 for URL: https://api.microsofttranslator.com/v2/http.svc/Translate?appid=Bearer+eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzY29wZSI6Imh0dHBzOi8vYXBpLm1pY3Jvc29mdHRyYW5zbGF0b3IuY29tLyIsInN1YnNjcmlwdGlvbi1pZCI6ImI0MDk0NjcwMDJkMzQ1OTVhZDljNWI3ZDA1NTcxMGNjIiwicHJvZHVjdC1pZCI6IlRleHRUcmFuc2xhdG9yLkYwIiwiY29nbml0aXZlLXNlcnZpY2VzLWVuZHBvaW50IjoiaHR0cHM6Ly9hcGkuY29nbml0aXZlLm1pY3Jvc29mdC5jb20vaW50ZXJuYWwvdjEuMC8iLCJhenVyZS1yZXNvdXJjZS1pZCI6Ii9zdWJzY3JpcHRpb25zLzExMTk0NjkyLTk1ZGEtNGU5Yi1hMDVhLTBiZjg0YTcxYzM3OC9yZXNvdXJjZUdyb3Vwcy9jc3MvcHJvdmlkZXJzL01pY3Jvc29mdC5Db2duaXRpdmVTZXJ2aWNlcy9hY2NvdW50cy9jc3MiLCJpc3MiOiJ1cm46bXMuY29nbml0aXZlc2VydmljZXMiLCJhdWQiOiJ1cm46bXMubWljcm9zb2Z0dHJhbnNsYXRvciIsImV4cCI6MTUwMTEzMDk2OX0.JPgvzprydjz5_cVi3pk23X1VxgmlqbcoL4bPADkxqYA&text=Acoustic Guitar Tuners&from=en&to=ar
The URL as such works in the browser:
Kindly help.
HTTP status code 400 is "Bad Request". Your query is faulty.
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_errors
The problem is AFAIK that your request contains spaces which are invalid.
&text=Acoustic Guitar Tuners&from=en&to=ar
You have to replace the spaces with for e.g. "+", like this:
&text=Acoustic+Guitar+Tuners&from=en&to=ar
See Spaces in URLs?
I hope this solves your problem. Good luck!
Related
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
I have an issue regarding OData querying with an Java Client.
If I use Postman, everything works as expected and I'm receiving a response from the web service with the metadata. But in my Java Client, which runs not on the SCP / HCP I'm receiving "400-Bad Request". I used the original Olingo libary.
I only used the $metadata Parameter, so there is no filter value or something else.
public void sendGet(String user, String password, String url) throws IOException, URISyntaxException {
// String userPassword = user + ":" + password;
// String encoding = Base64.encodeBase64String(userPassword.getBytes("UTF-8"));
URL obj = new URL(url);
URL urlToEncode = new URL(url);
URI uri = new URI(urlToEncode.getProtocol(), urlToEncode.getUserInfo(), urlToEncode.getHost(), urlToEncode.getPort(), urlToEncode.getPath(), urlToEncode.getQuery(), urlToEncode.getRef());
// open Connection
HttpURLConnection con = (HttpURLConnection) uri.toURL().openConnection();
// Basis Authentifizierung
con.setRequestProperty("Authorization", "Basic " + user);
// optional default is GET
con.setRequestMethod("GET");
// add request header
con.setRequestProperty("Content-Type", "application/xml");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
response.append("\n");
}
in.close();
// print result
System.out.println(response.toString());
// Schließt eine Vorhandene Verbindung
con.disconnect();
in User is already the encoded value. by manipulating this one, i'm receiving an authorization error, so already tested.
May somebody can help me in that case :)
Thanks in advance.
Tim
So I solved it by myself.
i added the statement con.setRequestProperty("Accept", "application/xml"); and it works fo me.
Maybe it could help somebody else.
I want to set a successful request to Neteller, I am trying to get an access token using the code from the Neteller documentation. However, it consistently fails with with the following exception:
java.io.IOException: Server returned HTTP response code: 401 for URL: https://test.api.neteller.com/v1/oauth2/token?grant_type=client_credentials
Here's the code (again, from the Neteller documentation):
String testUrl = " https://test.api.neteller.com";
String secureUrl = "https://api.neteller.com";
String url = testUrl;
if("live".equals(configBean.get("environment"))){
url = secureUrl;
}
url += "/v1/oauth2/token?grant_type=client_credentials";
String xml = "grant_type=client_credentials?grant_type=client_credentials";
xml = "";
String test = Base64.encodeBytes((accountID + ":" + secureID).getBytes());
try {
URL urls = new URL ("https://test.api.neteller.com/v1/oauth2/token?grant_type=client_credentials");
HttpURLConnection connection = (HttpURLConnection) urls.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty ("Authorization", "Bearer " + test);
connection.setRequestProperty ("Content-Type", "application/json");
connection.setRequestProperty ("Cache-Control", "no-cache");
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.flush();
wr.close();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String accessToken = "";
} catch(Exception e) {
e.printStackTrace();
}
Why is my implementation failing here?
There is nothing wrong with your code. The problem is that you are trying use a regular member account for the API integration, where you need to be using a merchant account for that. Below are the steps you will need to complete in order to get it to work:
You need to get a test merchant account (http://www.neteller.com/business/contact-sales/). Registering on www.neteller.com creates a regular member account, which cannot receive payments via the API.
Once you have a test merchant account, you will need to white-list the IP address from which you will be making requests to the API. (pg. 31 of the manual).
Then, you will need to add an application to it (pg. 32 of the manual).
Once you have added the application, use the "client ID" and "client secret" in the Authorization header - just like you do now, base64 encoded values, separated with colon (:).
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
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();