How to use Satang "orders/user" API with java? - java

I've built java code to use satang "orders/user" api.
But got 405 error.
Please help me.
I've built placeLimitOrder() function.
And used successfully.
Then getUserOrders() function also made with same rult.
But this function got 405 error.
I can't find the reason.
public String getUserOrders (String pair,String limit,String offset,String status,String side)
{
String req="limit="+limit+"&offset="+offset+"&pair="+pair+"&side="+side+"&status="+status;
String operation="orders/user";
String signature=getSignature(req);
URL url = new URL(baseUrl+operation);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput( true );
con.setInstanceFollowRedirects( false );
con.setRequestProperty("Authorization", "TDAX-API "+this.key);
con.setRequestProperty("Signature",signature);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("charset", "utf-8");
con.setRequestProperty("User-Agent", "java client");
con.setUseCaches( false );
JsonObject obj=new JsonObject();
obj.addProperty("limit", limit);
obj.addProperty("offset", offset);
obj.addProperty("pair", pair);
obj.addProperty("side", side);
obj.addProperty("status", status);
String json=obj.toString();
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(json);
wr.flush();
wr.close();
int responseCode=con.getResponseCode();
if(responseCode!=HttpURLConnection.HTTP_OK){
throw new BadResponseException(responseCode);
}
BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder result = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
Following code working well.
I can't find the reason.
public String placeLimitOrder(String amount,String pair,String price,String side) throws IOException, BadResponseException
{
Long lnonce=new Date().getTime();
String nonce=lnonce.toString();
String req="amount="+amount+"&nonce="+nonce+"&pair="+pair+"&price="+price+"&side="+side+"&type=limit";
String operation="orders/";
String signature=getSignature(req);
URL url = new URL(baseUrl+operation);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setDoOutput( true );
con.setInstanceFollowRedirects( false );
con.setRequestProperty("Authorization", "TDAX-API "+this.key);
con.setRequestProperty("Signature",signature);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("charset", "utf-8");
con.setRequestProperty("User-Agent", "java client");
con.setUseCaches( false );
JsonObject obj=new JsonObject();
obj.addProperty("amount", amount);
obj.addProperty("nonce", nonce);
obj.addProperty("pair", pair);
obj.addProperty("price", price);
obj.addProperty("side", side);
obj.addProperty("type", "limit");
String json=obj.toString();
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(json);
wr.flush();
wr.close();
int responseCode=con.getResponseCode();
if(responseCode!=HttpURLConnection.HTTP_OK){
throw new BadResponseException(responseCode);
}
BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder result = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}

public String getUserOrders(String pair,String limit,String offset,String status,String side) throws IOException, BadResponseException
{
String req="limit="+limit+"&offset="+offset+"&pair="+pair+"&side="+side+"&status="+status;
String operation="orders/user?"+req;
String signature=getSignature("");
URL url = new URL(baseUrl+operation);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setDoOutput( true );
con.setInstanceFollowRedirects( false );
con.setRequestProperty("Authorization", "TDAX-API "+this.key);
con.setRequestProperty("Signature",signature);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("charset", "utf-8");
con.setRequestProperty("User-Agent", "java client");
con.setUseCaches( false );
int responseCode=con.getResponseCode();
if(responseCode!=HttpURLConnection.HTTP_OK){
throw new BadResponseException(responseCode);
}
BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder result = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}

So if you are trying to do GET to https://api.tdax.com/api/orders/user
Headers should include:
Signature
Authentication
Query Parameters:
pair
limit
offset
status
side
From your code, it looks like you have put everything to the Signature.
Link to API docs
This is what you should fix:
URL. It should look like:
https://api.tdax.com/api/orders/user?pair=pairValue&limit=limitValue&offset=... add all the parameters and insert values.
Change request method to GET
Double-check your headers (Signature, Authentication).
Error code 405 - "bad request", which means most likely your request URL is bad. After you will fix URL, you should be able to get a different response code like 403/401 which should indicate that something is wrong with signature or authentication. In the best-case scenario, you will get 200 and then try to parse the JSON response.
Also, I don't recommend you to use HttpURLConnection, Generally, it’s NOT recommended to use this class, because the codebase is very old and outdated, it may not supports the new HTTP/2 standard, in fact, it’s really difficult to configure and use this class. Please consider using OkHttp, Apache HttpClient or other libraries.

Related

UTF-8 problem in response of SOAP request

When I make the SOAP request from SOAP UI it returns normal answer, but when I try from Java code it returns not understandable characters. I tried to convert answer to UTF8 format, but it did not help. Please advise a solution, may be something wrong with my SOAP request. Example of response: OÄžLU, bu it must be OĞLU or MÄ°KAYIL instead of MİKAYIL
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
String userCredentials = username + ":" + password;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));
con.setRequestProperty("Authorization", basicAuth);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "text/xml");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(myXML);
wr.flush();
wr.close();
String responseStatus = con.getResponseMessage();
System.out.println(responseStatus);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String xmlResponse = response.toString();
I tried:
ByteBuffer buffer = ByteBuffer.wrap(xmlResponse.getBytes("UTF-8"));
String converted = new String(buffer.array(), "UTF-8");
Try this:
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
The character encoding is set as part of the Content-Type header.
I believe you're accidentally mixing charsets, which is why it is not displaying properly.
Try adding the charset to Content-Type like so:
con.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
Would you try this?
con.setRequestProperty("Content-Type", "text/xml; charset=utf-8");

POST request works with POSTMAN but not in my Java application

I brief description of what I'm doing, I'm automating creating incidents in ServiceNow using API. I have tested with POSTMAN first and it works fine.
Now after I wrote the code, I try to post data, I got no respond from the server. what could be the problem?
if (method.equals("POST") )
{
url+= "api/now/table/incident";
}
else if (method.equals("GET")|| method.equals("PUT"))
{
url+= "api/now/table/incident/" + incident.getSys_id();
}
URL request_url = new URL(url);
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
connection = (HttpsURLConnection) request_url.openConnection();
// ((HttpsURLConnection) connection).setSSLSocketFactory(sslsocketfactory);
if (method.equals("POST") || method.equals("PUT"))
{
connection.setRequestProperty("Content-Type", "application/json");
}
else
{
connection.setRequestProperty("Accept", "application/json");
}
connection.setRequestProperty("User-Agent", "Mozilla/5.0"); // this was suggested as solution, but doesn't work.
connection.setRequestMethod(method);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Authorization", "Basic "+encoded);
if (method.equals("POST") || method.equals("PUT"))
{
JSONObject json = new JSONObject();
json.put("short_description",incident.getShort_description());
json.put("description", incident.getDescription());
json.put("assignment_group",incident.getAssignment_group());
json.put("priority",incident.getPriority());
json.put("impact",incident.getImpact());
OutputStream os = connection.getOutputStream();
os.write(json.toJSONString().getBytes(StandardCharsets.UTF_8));
os.close();
}
// read the respond
httpsCode = connection.getResponseCode();
if (httpsCode == HttpsURLConnection.HTTP_OK || httpsCode == 201)
{
//Read
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
String lines = null;
StringBuilder stringBuilder = new StringBuilder();
while ((lines = bufferedReader.readLine()) != null)
{
stringBuilder.append(lines);
}
bufferedReader.close();
result = stringBuilder.toString();
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(result);
String incident_number = json.get("incident_number").toString();
String sys_id = json.get("sys_id").toString();
incident.setIncident_number(incident_number);
incident.setSys_id(sys_id);
return null;
}
the error is related to timeout, a posted solution suggested to set up the header to a browser type. but that's also didn't work.

Java Post Connection Using Try with Resources

I want to implement the code for handling POST requests using try with resources.
Following is my code:
public static String sendPostRequestDummy(String url, String queryString) {
log.info("Sending 'POST' request to URL : " + url);
log.info("Data : " + queryString);
BufferedReader in = null;
HttpURLConnection con = null;
StringBuilder response = new StringBuilder();
try{
URL obj = new URL(url);
con = (HttpURLConnection) obj.openConnection();
// add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/json");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(queryString);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
log.info("Response Code : " + responseCode);
if (responseCode >= 400)
in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
else
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}catch(Exception e){
log.error(e.getMessage(), e);
log.error("Error during posting request");
}
finally{
closeConnectionNoException(in,con);
}
return response.toString();
}
I have the following concerns for the code:
How to introduce conditional statements in try with resources for the above scenario?
Is there a way to pass on the connection in try with resources? (It can be done using nested try-catch blocks since URL and HTTPConnection is not AutoCloseable, which itself is not a compliant solution)
Is using try with resources for the above problem is a better approach?
Try this.
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
try (AutoCloseable conc = () -> con.disconnect()) {
// add request headers
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.writeBytes(queryString);
}
int responseCode = con.getResponseCode();
try (InputStream ins = responseCode >= 400 ? con.getErrorStream() : con.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(ins))) {
// receive response
}
}
() -> con.disconnect() is a lambda expression which execute con.disconnect() at finally stage of the try statement.
1: You can use conditional statements inside try with resources statement also. Unfortunately you have to define new variable for this block and cannot use a predefined variable. ( variable in in your code)
try (BufferedReader in = (responseCode >= 400 ? new BufferedReader(new InputStreamReader(con.getErrorStream())) : new BufferedReader(new InputStreamReader(con.getInputStream())))) {
// your code for getting string data
}
2: I'm not sure HttpUrlConnection is AutoCloseable, So it might be a good idea to call the disconnect() yourself. I'm open to any suggestion on this one.
3: try with resources will definitely help you in managing the resources. But if you're confident that you're releasing the resources properly after use, then your code is fine.

Android Post request not posting any data on server

=====Updated========
Actually below code is fine, My problem is at server side.
=====Updated========
Below is my code,I am using HttpURLConnection but not able to send JSON data to server.
Please help me Thanks in advance
JSONObject jo = new JSONObject();
jo.put("ID", "25")
Log.e("test", jo.toString());
url = new URL(URL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.writeBytes(jo.toString());
wr.flush();
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer sb = new StringBuffer();
int chr;
while ((chr = is.read()) != -1) {
sb.append((char) chr);
}
line = sb.toString();
Log.e("json_temp", line);
rd.close();
Your code is fine, it doesn't show a blank array, but a string "Array()". I tried a resource test, and that's exactly what it showed me.
If you type in the URL in the browser, you should see the same thing.

Why Google Recaptcha returns false after a specific time in java?

I am using Google reCAPTCHA in my project. It works fine. But after a specific time, my code is returning the response value is false. It should be true.
Not always like this, but after 10 days(for example) returning false.I am not hitting any daily usage limit.
The problem is solving when I restart the server (apache tomcat).
My code is:
public static boolean verify(String gRecaptchaResponse) throws IOException {
if (gRecaptchaResponse == null || "".equals(gRecaptchaResponse)) {
return false;
}
try {
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String postParams = "secret=" + secret + "&response="
+ gRecaptchaResponse;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + postParams);
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());
//parse JSON response and return 'success' value
JsonReader jsonReader = Json.createReader(new StringReader(response.toString()));
JsonObject jsonObject = jsonReader.readObject();
jsonReader.close();
return **jsonObject.getBoolean("success");**
} catch(Exception e){
e.printStackTrace();
return false;
}
}

Categories

Resources