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
Related
Good afternoon. I am trying to connect Android app to http://localhost:3000/ ( but in code I use an emulator's ip).
The error is "W/System.err: java.net.ConnectException: Connection refused"
Could you help me to find an error? Other posts were not useful for me.
public String execute() {
String line;
StringBuilder outputStringBuilder = new StringBuilder();
try {
StringBuilder urlString = new StringBuilder(baseUrl + urlResource);
if (!urlPath.equals("")) {
urlString.append("/" + urlPath); }
if (parameters.size() > 0 && httpMethod.equals("POST")) {
payload = getPayloadAsString();
urlString.append("?" + payload); }
URL url = new URL(urlString.toString());
String encoding = Base64Encoder.encode(email + ":" + password);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(httpMethod);
connection.setRequestProperty("Authorization", "Basic " + encoding);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "text/plain");
connection.connect();
if (httpMethod.equals("GET") || httpMethod.equals("PUT")) {
payload = getPayloadAsString();
connection.setDoInput(true);
connection.setDoOutput(true);
try {
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
headerFields = connection.getHeaderFields();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = br.readLine()) != null) {
outputStringBuilder.append(line);
}
} catch (Exception ex) {}
connection.disconnect();
}
else {
InputStream content = (InputStream) connection.getInputStream();
headerFields = connection.getHeaderFields();
BufferedReader in = new BufferedReader(new InputStreamReader(content));
while ((line = in.readLine()) != null) {
outputStringBuilder.append(line);} }
} catch (Exception e) {
e.printStackTrace(); }
if (!outputStringBuilder.toString().equals("")) {
lastResponse = outputStringBuilder.toString(); }
return outputStringBuilder.toString(); }}
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();
}
I want to convert a HTTP GET request to a HTTP PATCH request. I am accessing TFS APIs and I want to lock my build automatically by using a patch request.
Currently I am getting all the information by GET method. Now I want to update keepForever from false to true using the HTTP PATCH method. By GET method I am able to do that but now I have to do that by HTTP Patch method.
Can someone help me converting the below code from GET method to POST method?
public class Test_URL_Req {
public static String getURLResponse(String url) {
try {
System.out.println("\nSending 'GET' request to URL : " + url);
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
int responseCode = con.getResponseCode();
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);
// System.out.println(response);
}
in.close();
return response.toString();
} catch (Exception e) {
System.out.println(e);
}
return null;
}
public static void main(String[] args) throws JSONException{
String url = "https://tfs.tpsonline.com/IRIS%204.0%20Collection/Main/_apis/build/definitions?api-version=4.1";
//String url1 ="https://tfs.tpsonline.com/IRIS%204.0%20Collection/Main/_apis/build/builds?api-version=4.1&definitions=" + Def_id +"&resultFilter=succeeded&$top=1";
String response = getURLResponse(url);
// String response1 = getURLResponse(url1);
JSONObject obj_JSONObject = new JSONObject(response.toString());
JSONArray obj_JSONArray = obj_JSONObject.getJSONArray("value");
String Def_id=null;
for(int i=0; i<obj_JSONArray.length();i++)
{
JSONObject obj_JSONObject2 = obj_JSONArray.getJSONObject(i);
String value = obj_JSONObject2.getString("name");
String toSearch= "DEVOPS";
if(value.equals(toSearch)){
System.out.println("STATUS:-");
System.out.println(value);
String result =obj_JSONObject2.getString("name");
System.out.println("BUILD NAME");
System.out.println(result);
Def_id = obj_JSONObject2.get("id").toString();
System.out.println("DEFINATION ID");
System.out.println(Def_id);
break;
}
}
if (Def_id != null)
{
String url1 ="https://tfs.tpsonline.com/IRIS%204.0%20Collection/Main/_apis/build/builds?api-version=4.1&definitions=" + Def_id +"&resultFilter=succeeded&$top=1";
String response1 = getURLResponse(url1);
JSONObject obj_JSONObject1 = new JSONObject(response1.toString());
JSONArray obj_JSONArray1 = obj_JSONObject1.getJSONArray("value");
String Build_id=null;
for(int i=0; i<obj_JSONArray1.length();i++)
{
JSONObject obj_JSONObject2 = obj_JSONArray1.getJSONObject(i);
String value = obj_JSONObject2.getString("result");
//String value = obj_JSONObject2.get("id").toString();
//System.out.println(value);
String toSearch1= "succeeded";
if(value.equals(toSearch1)){
System.out.println("#######################################");
System.out.println("RESULT");
System.out.println(value);
String result =obj_JSONObject2.getString("status");
System.out.println("STATUS");
System.out.println(result);
Build_id = obj_JSONObject2.get("id").toString();
System.out.println("BUILD ID");
System.out.println(Build_id);
//boolean keepForever =obj_JSONObject2.getBoolean("keepForever");
//if(keepForever == false)
//{
// keepForever=true;
//}
// System.out.println(keepForever);
}
}
if (Build_id != null)
{
String url2= "https://tfs.tpsonline.com/IRIS%204.0%20Collection/Main/_apis/build/builds?api-version=4.1&buildNumber=" + Build_id;
String response2 = getURLResponse(url2);
JSONObject obj_JSONObject2 = new JSONObject(response2.toString());
JSONArray obj_JSONArray2 = obj_JSONObject2.getJSONArray("value");
for(int i=0; i<obj_JSONArray2.length();i++)
{
JSONObject obj_JSONObject3 = obj_JSONArray2.getJSONObject(i);
String value = obj_JSONObject3.getString("result");
//String value = obj_JSONObject2.get("id").toString();
//System.out.println(value);
String toSearch1= "succeeded";
if(value.equals(toSearch1)){
boolean keepForever =obj_JSONObject3.put("keepForever", false) != null;
if(keepForever == false)
{
keepForever = true;
}
System.out.println("#######################################");
System.out.println(keepForever);
}
}
}
}
}
}
You can just use the below to build PATCH request. However, you should also make sure that your server supports PATCH as its generally unsupported.
public static String getPatchResponse( String url){
try {
System.out.println("\nSending 'PATCH' request to URL : " + url);
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("PATCH");
con.setRequestProperty("Accept", "application/json");
int responseCode = con.getResponseCode();
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);
//System.out.println(response);
}
in.close();
return response.toString();
} catch (Exception e) {
System.out.println(e);
}
return null;
}
I use the following Java code in a Bean to read a URL's content:
String url;
String inputLine;
StringBuilder srcCode=new StringBuilder();
public void setUrl (String value) {
url = value;
}
private void scanWebPage() throws IOException {
try {
URL dest = new URL(url);
URLConnection yc = dest.openConnection();
yc.setUseCaches(false);
BufferedReader in = new BufferedReader(new
InputStreamReader(yc.getInputStream()));
while ((inputLine = in.readLine()) != null)
srcCode = srcCode.append (inputLine);
in.close();
} catch (FileNotFoundException fne) {
srcCode.append("File Not Found") ;
}
}
The code works fine for most URL's, but does not work for redirected URLs. How can I update the above code to read content from redirected URLs? For redirected URLs, I get "File Not Found".
Give the following a go:
HttpURLConnection yc = (HttpURLConnection) dest.openConnection();
yc.setInstanceFollowRedirects( true );
In context to your code above:
`String url = "http://java.sun.com";
String inputLine;
StringBuilder srcCode=new StringBuilder();
URL dest = new URL(url);
HttpURLConnection yc = (HttpURLConnection) dest.openConnection();
yc.setInstanceFollowRedirects( true );
yc.setUseCaches(false);
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
while ((inputLine = in.readLine()) != null) {
srcCode = srcCode.append (inputLine);
}
in.close();`
Modified further to help you diagnose what is going on. This code turns off auto redirection and then manually follows the Location headers printing out as it goes along.
#Test
public void f() throws IOException {
String url = "http://java.sun.com";
fetchURL(url);
}
private HttpURLConnection fetchURL( String url ) throws IOException {
URL dest = new URL(url);
HttpURLConnection yc = (HttpURLConnection) dest.openConnection();
yc.setInstanceFollowRedirects( false );
yc.setUseCaches(false);
System.out.println( "url = " + url );
int responseCode = yc.getResponseCode();
if ( responseCode >= 300 && responseCode < 400 ) { // brute force check, far too wide
return fetchURL( yc.getHeaderField( "Location") );
}
System.out.println( "yc.getResponseCode() = " + yc.getResponseCode() );
return yc;
}
its not the debuggin of your prog , but you can consider this one
public class GetURLData
{
public static void main(String args[])
{
String url = "the url you want the response from";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse response;
StringBuilder builder= new StringBuilder();
try
{
response = httpClient.execute(httpPost);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
char[] buf = new char[8000];
int l = 0;
while (l >= 0)
{
builder.append(buf, 0, l);
l = in.read(buf);
}
System.out.println(builder.toString);
} catch (Exception e)
{
System.out.println("Exception is :"+e);
e.printStackTrace();
}
}
}
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
}
}