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.
Related
I'm trying to login to a portal. It works using Postman. When I try the same request using plain Java or OkHttp the login fails and I will be redirected to the login page.
HttpUrl.Builder httpBuilder = HttpUrl.parse("https://test58.cashctrl.com/auth/login.html").newBuilder();
httpBuilder.addQueryParameter("JMCF_AUTH_EMAIL", "email");
httpBuilder.addQueryParameter("JMCF_AUTH_PASSWORD", "password");
Request request = new Request.Builder()
.url(httpBuilder.build())
.get()
.build();
I know the Url looks weird but it works this way using Postman or even simply use a browser.
Alternative with plain Java, which I tried:
Map<String, String> parameters = new HashMap<>();
parameters.put(PARAM_EMAIL, EMAIL);
parameters.put(PARAM_PASSWORD, PASSWORD);
URL url = new URL(LOGIN_URL + "?" + ParameterStringBuilder.getParamsString(parameters));
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setInstanceFollowRedirects(true);
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes(ParameterStringBuilder.getParamsString(parameters));
out.flush();
out.close();
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine + "\n");
}
in.close();
con.disconnect();
System.out.println(status);
System.out.println(content.toString());
Postman must be doing something special or also a browser which I don't see.
I had the same issue, I got to know that Postman has "code" feature. Below the send button you can see the code option it will generate the code for you. There is a list of language to choose from and java is one of them. Do check that out. Also you must be missing the cookie, see the temporary headers in Postman add all in your code and do include the cookie one.
Thanks I hope it helps.
When sending a get request to try and retrieve a challonge bracket, I get the robots.txt file instead of the actual bracket. If I copy and paste the same url into my browser, I get the intended JSON bracket. I was wondering what I was doing wrong and how I could make it so that the following Java method actually returns the bracket instead of the metaname=robots text file.
public String httpGett(String url,String userAgent) throws Exception{
String USER_AGENT = userAgent;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
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);
}
in.close();
//System.out.println(response.toString());
return(response.toString());
}
For example, if the url I sent was
https://challonge.com/api/tournaments/example.json?include_matches=1&include_participants=1&api_key=[MY
API KEY]
And I typed the url into my browser I would get:
http://pastebin.com/4W4kmdJV
And if I used my Java method to send the get request I would get:
http://pastebin.com/ifYSSzu3
How can I get the correct bracket info from my Java method?
So I managed to figure out what I was doing wrong, kind of.
When I use:
https://api.challonge.com/v1/tournaments/example.json?include_matches=1&include_participants=1&api_key=[MYAPIKEY]
Instead of the previous link, the metaname=robots link stopped appearing and I got the correct bracket information.
I'm trying to send a PUT request from a Java app to a server. I successfully send GET, POST and DELETE requests but the PUT one won't succeed (I'm getting a 401 Error with the code below, 405 Error with an other code using the HttpPut of the apache package).
I'm using java.net.HttpURLConnection, here is a small region of my code :
URL obj = new URL(urlPost);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add request header
con.setRequestMethod(typeRequest); //typeRequest = PUT
String credentials = adminOC + ":" + pwdOC;
String encoding = Base64.encode(credentials.getBytes("UTF-8"));
con.setRequestProperty("Authorization", String.format("Basic %s", encoding));
if (!typeRequest.equals("GET")){
con.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.writeBytes(postParam);
wr.flush();
}
}
if (con.getResponseCode() == 200){
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
response += inputLine;
}
}
}
I tried sending my PUT parameters the "POST" way and also directly in the URL.
It seems to be an error from my Java code and not from the server because I tried to do the PUT request with cURL and it worked.
Thanks for reading, I hope you will be able to give me some hints to debug the problem.
What is missing in your code is con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
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 (:).
update : this is a duplicate,
i'm building a Proxy-custom-tag with grails taglib, per default it makes a get-request, now i'm facing the problem, that it should be able to handle Post-requests too,#
and i'm able to check the request-method and conditionally set the openConnection method to post if necessary, but i dont know how to append the post-params to the request.
here 's my code so far
def wordpressContent = { attrs, body ->
def url
def requestMethod = request.getMethod()
def queryString = request.getQueryString()?'&'+request.getQueryString():''
def content
println "method :"+requestMethod
println "params == "+params // <- inside here are the post-parameters
url = grailsApplication.config.wordpress.server.url+attrs.pageName+'?include=true'+queryString
try {
content = url.toURL().openConnection().with { conn ->
if(requestMethod == 'POST'){
println "Its a POST"
conn.setRequestMethod("POST")
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// HOW to append the params here ?
}
readTimeout = 6000
if( responseCode != 200 ) {
throw new Exception( 'Not Ok' )
}
conn.content.withReader { r ->
r.text
}
}
}
catch( e ) {
println "exception : "+e
content="<div class='float' style='margin-top:10px;width:850px;background-color:white;border-radius:5px;padding:50px;'>Hier wird gerade gebaut</div>"
}
out << content
}
im very stuck here right now, i found answers saying to use this syntax
Writer wr = new OutputStreamWriter(conn.outputStream)
wr.write(postParams)
wr.flush()
wr.close()
but i dont know how to include that to my existing code,
for any hints thanks in advance
update: my solution was to build up the post-parameter-querystring by iterating over the params object in this pattern "xyz=zyx&abc=cba" and write it to the outputStream like above
// HTTP POST request
private void sendPost() throws Exception {
String url = "https://selfsolve.apple.com/wcResults.do";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
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);
}
in.close();
//print result
System.out.println(response.toString());
}
you are using grails so you can also use groovy HTTPBuilder like below
http://groovy.codehaus.org/modules/http-builder/doc/