I'm going to use satang api with java.
This is reference book.
https://docs.satang.pro/authentication
I've completed public request code with java.
private String publicOperation(String operation) throws IOException, BadResponseException {
StringBuilder result = new StringBuilder();
URL url = new URL(baseUrl+operation);
//URL url_ = new URL("https://api.tdax.com/api/orders/?pair=btc_thb");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("User-Agent", "java client");
con.setRequestMethod("GET");
//https://api.tdax.com/api/orders/?pair=btc_thb
int responseCode=con.getResponseCode();
if(responseCode!=HttpURLConnection.HTTP_OK){
throw new BadResponseException(responseCode);
}
BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
Who can make private http request with any program language?
I have the same problem
But I use google sheet to import
function satang(){
var rows=[],obj_array=null;
try {obj_array=JSON.parse(UrlFetchApp.fetch("https://api.tdax.com/api/orders/?pair=btc_thb").getContentText());} catch (e) {obj_array=null;}
if (obj_array!=null){
for (r in obj_array) {rows.push([parseFloat(obj_array[r].bid),parseFloat(obj_array[r].price),parseFloat(obj_array[r].amount),parseFloat(obj_array[r].ask)]);}
var ss=SpreadsheetApp.getActiveSpreadsheet(),sheet=ss.getSheetByName('Satang');ss.getRange("Satang!A1").setValue(new Date());
try {var range=sheet.getRange(2,1,sheet.getLastRow(),6).clearContent();} catch(e) {Logger.log("error");}
if (rows==null||rows=="") {Browser.msgBox("Oops, no data from satang. Please try again"); return false;}
range=sheet.getRange(2,1,rows.length,4); range.setValues(rows);
}
}
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("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("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();
}
Related
I am trying to create a post request with auth token but I am getting null response. Can you please help me.Can you please let me know what am I missing in the code ?
public static void main(String[] args) {
try {
String url = "https://test.abc.com/";
String token="XXXXXX-abcd-496a-ae73-7659587896";
URL object = new URL(url);
HttpURLConnection con = (HttpURLConnection) object.openConnection();
con.setDoInput(true);
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Authorization", "Bearer " + token);
//Display what the GET request returns
StringBuilder sb = new StringBuilder();
int HttpResult = con.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream(), "utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
System.out.println(con.getResponseMessage());
} else {
System.out.println(con.getResponseMessage());
}
} catch (Exception e) {
System.out.println(e);
}
}
}
Welcome all, I'm currently working on a web-service and I'm having a lot of trouble to make this method work with characters like ñ, ç, á, è,... It's seems to be related with my Input stream, it doesn't seem to be encoding properly, here's the code:
private static String sendPost(String url, Map<String, JSONObject> params) throws Exception {
String responseString;
StringBuilder urlParameters = new StringBuilder(400);
if (params != null) {
for (Entry<String, JSONObject> entry : params.entrySet()) {
urlParameters.append(entry.getKey()).append("=").append(entry.getValue().toString()).append("&");
}
}
url += urlParameters.toString();
url = url.replace(" ", "%20");
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("charset", "utf-8");
con.setDoOutput(true);
int responseCode = con.getResponseCode();
if (responseCode == HttpStatus.SC_OK) {
BufferedReader in = null;
StringBuffer response = null;
try{
//when i check 'con' all seems to be fine
in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}finally{
in.close();
}
responseString = response.toString();
} else {
responseString = new StringBuilder(25).append(responseCode).toString();
}
return responseString;
}
Example:
Inside "con" http:\direction.dom\data\W-S\something?param={example:"castaña"}
and InputStream returns: http:\direction.dom\data\W-S\something?param={example:"casta�a"}
Thanks in advance.
This is a really tricky case because you're dealing with HTTP params. Those can be in any encoding that the user enters in your browser.
Based on your example, your user sends his data in something other than UTF-8. It can be ISO-8859-1, ISO-8859-15 or windows-1252.
You can make push your users towards UTF-8 by setting the right HTTP header to your web form: response.setContentType("text/xml; charset=utf-8):
My partner just figure how to solve it:
private static String sendPost(String url, Map<String, JSONObject> params) throws Exception {
String responseString;
StringBuilder urlParameters = new StringBuilder(400);
if (params != null) {
for (Entry<String, JSONObject> entry : params.entrySet()) {
urlParameters.append(entry.getKey()).append("=").append(entry.getValue().toString()).append("&");
}
}
url = url.replace(" ", "%20");
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("accept-charset", "UTF-8");
con.setRequestProperty("content-type", "application/x-www-form-urlencoded; charset=utf-8");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(wr, "UTF-8"));
writer.write(urlParameters.toString());
writer.close();
wr.close();
int responseCode = con.getResponseCode();
if (responseCode == HttpStatus.SC_OK) {
BufferedReader in = null;
StringBuffer response = null;
try{
in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}finally{
in.close();
}
responseString = response.toString();
} else {
responseString = new StringBuilder(25).append(responseCode).toString();
}
return responseString;
}
I'm trying to send push notifications via Appcelerator rest API through my java server. I've been able to login, but when I try to send the notification I get 422 error (Unprocessable entity)
Here´s my login:
String SENDER_ID = "55694f177eead29359bda190";
String API_KEY = "bRhpzjfpHakUkYeVGbCBoFLGpqLTeKIm";
String API_USR = "tuin";
String API_PAS = "tuin123";
String URL_ACS = "https://api.cloud.appcelerator.com/v1/";
URL url = null;
URLConnection uc = null;
String idSession=null;
try {
url = new URL(URL_ACS+"users/login.json?key="+API_KEY+"&login="+API_USR+"&password="+API_PAS+"");
uc = url.openConnection();
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
if (conn.getResponseCode() != 200) {
throw new Exception(conn.getResponseMessage());
}
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
String respuesta=sb.toString();
if(respuesta.contains("status\":\"ok") && respuesta.contains("code\":200") ){
int number=sb.indexOf("session_id");
String meta=sb.substring(number+13, number+60);
int fin=meta.indexOf("\"");
idSession=meta.substring(0, fin);
}else{
System.out.println("No ID");
}
} catch (Exception e) {
throw new Exception("Trouble "+e);
}
Then I try to send the notification
public String sendPush(String date,String name, String text, String title,String session_id) throws Exception{
String URL_ACS = "https://api.cloud.appcelerator.com/v1/";
String API_KEY = "bRhpzjfpHakUkYeVGbCBoFLGpqLTeKIm";
URL url = null;
HttpURLConnection uc = null;
String idSession=null;
try {
String rt=URL_ACS+"push_notification/notify.json?key="+API_KEY+"";
url=new URL(rt);
uc = (HttpURLConnection) url.openConnection();
uc.setDoInput(true);
uc.setDoOutput(true);
uc.setRequestProperty("Content-Type", "application/json");
uc.setRequestProperty("Accept", "application/json");
uc.setRequestProperty("Cookie","_session_id="+session_id);
JSONObject cred = new JSONObject();
JSONObject push = new JSONObject();
JSONObject chan = new JSONObject();
cred.put("alert","test");
cred.put("title","title");
cred.put("icon","icon_notifi");
cred.put("vibrate",true);
cred.put("sound","default");
push.put("payload",cred);
//chan.put("push_notification", push);
System.out.println(push.toString());
String responseJSON=push.toString().replace("{\"payload\":", "{channel=\"noti\",to_ids=\"everyone\",payload=");
OutputStreamWriter wr= new OutputStreamWriter(uc.getOutputStream());
wr.write(responseJSON);
if (uc.getResponseCode() != 200) {
throw new Exception(uc.getResponseMessage());
}
InputStream is = uc.getInputStream();
BufferedReader rd = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
uc.disconnect();
System.out.println("The content was: " + sb.toString());
} catch (Exception e) {
throw new Exception("Trouble: "+e);
}
return idSession;
}
In the second part I got 422 Error.
I got the same problem. I fixed changing to Admin: yes the user that I'm using.
http://docs.appcelerator.com/arrowdb/latest/#!/guide/admin_access
I can not see what is wrong with this code:
JSONObject msg; //passed in as a parameter to this method
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setDoInput(true);
httpCon.setUseCaches(false);
httpCon.setRequestProperty( "Content-Type", "application/json" );
httpCon.setRequestProperty("Accept", "application/json");
httpCon.setRequestMethod("POST");
OutputStream os = httpCon.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
msg.write(osw);
osw.flush();
osw.close();
os.close(); //probably overkill
On the server, I am getting no post content at all, a zero length string.
Try
...
httpCon.setRequestMethod("POST");
httpCon.connect(); // Note the connect() here
...
OutputStream os = httpCon.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
...
osw.write(msg.toString());
osw.flush();
osw.close();
to send data.
to retrieve data try:
BufferedReader br = new BufferedReader(new InputStreamReader( httpCon.getInputStream(),"utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
System.out.println(""+sb.toString());
public String sendHTTPData(String urlpath, JSONObject json) {
HttpURLConnection connection = null;
try {
URL url=new URL(urlpath);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream());
streamWriter.write(json.toString());
streamWriter.flush();
StringBuilder stringBuilder = new StringBuilder();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(streamReader);
String response = null;
while ((response = bufferedReader.readLine()) != null) {
stringBuilder.append(response + "\n");
}
bufferedReader.close();
Log.d("test", stringBuilder.toString());
return stringBuilder.toString();
} else {
Log.e("test", connection.getResponseMessage());
return null;
}
} catch (Exception exception){
Log.e("test", exception.toString());
return null;
} finally {
if (connection != null){
connection.disconnect();
}
}
}`
call this methopd in doitbackground in asynctask
HttpURLConnection is cumbersome to use. With DavidWebb, a tiny wrapper around HttpURLConnection, you can write it like this:
JSONObject msg; //passed in as a parameter to this method
Webb webb = Webb.create();
JSONObject result = webb.post("http://my-url/path/to/res")
.useCaches(false)
.body(msg)
.ensureSuccess()
.asJsonObject()
.getBody();
If you don't like it, there is a list of alternative libraries on the link provided.
Why should we all write the same boilerplate code every day? BTW the code above is more readable and less error-prone. HttpURLConnection has an awful interface. This has to be wrapped!
Follow this example:
public static PricesResponse getResponse(EventRequestRaw request) {
// String urlParameters = "param1=a¶m2=b¶m3=c";
String urlParameters = Piping.serialize(request);
HttpURLConnection conn = RestClient.getPOSTConnection(endPoint, urlParameters);
PricesResponse response = null;
try {
// POST
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
// RESPONSE
BufferedReader reader = new BufferedReader(new InputStreamReader((conn.getInputStream()), StandardCharsets.UTF_8));
String json = Buffering.getString(reader);
response = (PricesResponse) Piping.deserialize(json, PricesResponse.class);
writer.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
conn.disconnect();
System.out.println("PricesClient: " + response.toString());
return response;
}
public static HttpURLConnection getPOSTConnection(String endPoint, String urlParameters) {
return RestClient.getConnection(endPoint, "POST", urlParameters);
}
public static HttpURLConnection getConnection(String endPoint, String method, String urlParameters) {
System.out.println("ENDPOINT " + endPoint + " METHOD " + method);
HttpURLConnection conn = null;
try {
URL url = new URL(endPoint);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "text/plain");
} catch (IOException e) {
e.printStackTrace();
}
return conn;
}
this without json String post data to server
class PostLogin extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String response = null;
Uri.Builder builder= new Uri.Builder().appendQueryParameter("username","amit").appendQueryParameter("password", "amit");
String parm=builder.build().getEncodedQuery();
try
{
response = postData("your url here/",parm);
}catch (Exception e)
{
e.printStackTrace();
}
Log.d("test", "response string is:" + response);
return response;
}
}
private String postData(String path, String param)throws IOException {
StringBuffer response = null;
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
// connection.setRequestProperty("Content-Type", "application/json");
// connection.setRequestProperty("Accept", "application/json");
OutputStream out = connection.getOutputStream();
out.write(param.getBytes());
out.flush();
out.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
response = new StringBuffer();
while ((line = br.readLine()) != null) {
response.append(line);
}
br.close();
}
return response.toString();
}
I am using this code to send data to the site where my gae-python app is deployed .But I dont know how to receive it on the other end.
protected void tryLogin(String mUsername, String mPassword)
{
HttpURLConnection connection;
OutputStreamWriter requestself = null;
URL url = null;
String response = null;
String parameters = "username="+mUsername+"&password="+mPassword;
try
{
url = new URL("http://www.pranshutrial3.appspot.com");
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
requestself = new OutputStreamWriter(connection.getOutputStream());
requestself.write(parameters);
requestself.flush();
requestself.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
// Response from server after login process will be stored in response variable.
response = sb.toString();
// You can perform UI operations here
Toast.makeText(this,"Message from Server: \n"+ response, Toast.LENGTH_LONG).show();
isr.close();
reader.close();
}
catch(IOException e)
{
// Error
}
}