This is my java code i am repeating the same steps for url and url1 so i want make a function in which i place the my url code seperate and url1 code seperate then call it in a main class. First I want to access String url and then I want to access String url1.As I am new in java so I am new in java so I am not able to enclose it into function
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONObject;
public class Test_URL_Req {
public static void main(String[] args){
// TODO Auto-generated method stub
try {
String id ="301";
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=" + id +"&resultFilter=succeeded&$top=1";
URL obj = new URL(url);
URL obj1 = new URL(url1);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
HttpURLConnection con1 = (HttpURLConnection) obj1.openConnection();
int responseCode = con.getResponseCode();
int responseCode1 = con1.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
System.out.println("\nSending 'GET' request to URL : " + url1);
System.out.println("Response Code : " + responseCode1);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
BufferedReader in1 = new BufferedReader(
new InputStreamReader(con1.getInputStream()));
String inputLine;
String inputLine1;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
//System.out.println(response);
}
StringBuffer response1 = new StringBuffer();
while ((inputLine1 = in1.readLine()) != null) {
response1.append(inputLine1);
//System.out.println(response1);
}
in.close();
JSONObject obj_JSONObject = new JSONObject(response.toString());
JSONObject obj_JSONObject1 = new JSONObject(response1.toString());
JSONArray obj_JSONArray = obj_JSONObject.getJSONArray("value");
JSONArray obj_JSONArray1 = obj_JSONObject1.getJSONArray("value");
for(int i=0; i<obj_JSONArray.length();i++)
{
JSONObject obj_JSONObject2 = obj_JSONArray.getJSONObject(i);
String value = obj_JSONObject2.getString("name");
//String value = obj_JSONObject2.get("id").toString();
//System.out.println(value);
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);
String Def_id = obj_JSONObject2.get("id").toString();
System.out.println("DEFINATION ID");
System.out.println(Def_id);
break;
}
}
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);
String Def_id = obj_JSONObject2.get("id").toString();
System.out.println("BUILD ID");
System.out.println(Def_id);
boolean keepForever =obj_JSONObject2.getBoolean("keepForever");
if(keepForever == false)
{
keepForever=true;
}
System.out.println(keepForever);
}
}
} catch (Exception e) {
System.out.println(e);
}
}
}
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();
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;
}
In main method -
public static void main(String[] args){
String url = "....";
String url1 =".....";
String response = getURLResponse(url);
String response1 = getURLResponse(url1);
JSONObject obj_JSONObject = new JSONObject (response);
JSONObject obj_JSONObject1 = new JSONObject(response1);
...
}
Create a method that takes a String and it appears you want a StringBuffer response...
public StringBuffer doSomething(String url){
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
int responseCode = con.getResponseCode();
//etc
return response;
}
And just pass your two URLs to it from the main:
String url = "https://tfs.tpsonline...
StringBuffer response = doSomething(url);
Related
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 try to send POST data to a Website. But the "login" will not work.
Slowly i dont know why. There are quite a lot of ways to login to a website without browser-ui. What is the "best" method to login here ?
I uses Jsoup and "normal" HttpURLConnection. With Selenium it works fine, but very slow =(
import com.gargoylesoftware.htmlunit.util.Cookie;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.*;
import org.jsoup.nodes.Document;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.*;
import java.util.List;
import java.util.Map;
public class postget {
private static final String USER_AGENT = "Mozilla/5.0";
private static final String GET_URL = "https://de.metin2.gameforge.com/";
private static final String POST_URL = "https://de.metin2.gameforge.com:443/user/login?__token=";//+token
private static final String POST_PARAMS = "username=USERNAME"+"password=PASSWORD";
static final String COOKIES_HEADER = "Set-Cookie";
public static void main(String[] args) throws IOException {
String var = sendGET();
String var1 =var.substring(0,var.indexOf(";"));
String var2 =var.substring(var.indexOf(";")+1,var.indexOf(":"));
String token =var.substring(var.indexOf(":")+1);
//sendPOST(token,cookie);
jsoup(cookie(),token);
}
private static String sendGET() throws IOException {
URL obj = new URL(GET_URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // success
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 veri1=response.substring(response.indexOf("verify-v1")+20,response.indexOf("verify-v1")+63);
String veri2=response.substring(response.indexOf("verify-v1")+104,response.indexOf("verify-v1")+147);
String token=response.substring(response.indexOf("token")+6,response.indexOf("token")+38);
return (veri1+";"+veri2+":"+token);
} else {
System.out.println("GET request not worked");
return " ";
}
}
private static String cookie() throws IOException{
String realCookie="";
URL obj = new URL(GET_URL);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
java.net.CookieManager msCookieManager = new java.net.CookieManager();
Map<String, List<String>> headerFields = connection.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if (cookiesHeader != null) {
for (String cookie : cookiesHeader) {
msCookieManager.getCookieStore().add(null,HttpCookie.parse(cookie).get(0));
}
}
List<HttpCookie> cookiess = msCookieManager.getCookieStore().getCookies();
if (cookiess != null) {
if (cookiess.size() > 0) {
for (HttpCookie cookie : cookiess) {
realCookie = cookie.toString().substring(cookie.toString().indexOf("=")+1);
return(realCookie);
}
}
}
return(realCookie);
}
private static void sendPOST(String token,CookieManager msCookieManager) throws IOException {
URL obj = new URL(POST_URL+token);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
if (msCookieManager != null) {
List<HttpCookie> cookies = msCookieManager.getCookieStore().getCookies();
if (cookies != null) {
if (cookies.size() > 0) {
for (HttpCookie cookie : cookies) {
String realCookie = cookie.toString().substring(cookie.toString().indexOf("=")+1);
}
con.setRequestProperty("Cookie", StringUtils.join(cookies, ";"));
}
}
}
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { //success
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
if(response.indexOf("form-login")>0){
System.out.println("NOPE");
}
if(response.indexOf("logout")>0){
System.out.println("YES");
}
} else {
System.out.println("POST request not worked");
}
}
private static void jsoup(String cookie,String token) throws IOException{
Document response = Jsoup.connect("https://de.metin2.gameforge.com/")
.referrer("https://de.metin2.gameforge.com/main/index?__token=5"+token)
.cookie("Cookie","gf-locale=de_DE; _ga=GA1.2.404625572.1501231885; __auc=a02de56115d8864ad2bd7ad8120; pc_idt=ANu-cNegKMzU8CAsBQAHIu1cRlXEEUD1ka6NvJXWqO4sVVaLIsqSFPyZFt8dXHKcrhrB_u2FFdQnD-2vsA377NnVgjkrKn-3qzi5Q3LXbzgnbbmIEir4zYNCddPbjCUg9cVpSU4GP-CvU53XhrQ6_MWP9tOYNdjCqRVIPw; SID="+cookie+"; __utma=96667401.404625572.1501231885.1503225538.1503232069.15; __utmc=96667401; __utmz=96667401.1501247623.3.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)")
//.data("X-DevTools-Emulate-Network-Conditions-Client-Id","c9bbb769-df80-47ff-8e25-e582de026ecc")
.userAgent("Mozilla")
.data("username", "USERNAME")
.data("password", "PASSWORD")
.post();
System.out.println(response);
}
}
}
The var1 and var1 are unnecessary.
They was my first idea to send with my POST.
Here is a picture if the login-form:
And of HttpClient
i am trying to do an android app to write some datas on MySQL database but it does not work i did a Java class for this and i think the problem comes from this. Here is my code :
public class BackgroundTask extends AsyncTask<String, Void, String> {
Context ctx;
BackgroundTask(Context ctx) {this.ctx = ctx;}
#Override
protected String doInBackground(String... params) {
String reg_url = "http://localhost:8080/project/register.php";
String method = params[0];
if (method.equals("register")) {
String name = params[1];
String password = params[2];
String contact = params[3];
String country = params[4];
try {
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8") + "&" +
URLEncoder.encode("contact", "UTF-8") + "=" + URLEncoder.encode(contact, "UTF-8") + "&" +
URLEncoder.encode("country", "UTF-8") + "=" + URLEncoder.encode(country, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
os.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
return "Registration success";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
Actually what i would like is to save name, password, contact and country in my database. The problem is this : "Registration success" is never returned it is always null. But i don't know why. When i try to compile it looks like there is no errors and i can see the app.
Thank you very much for your help !
Edit : This is the register.php :
<?php
require "init.php";
$u_name=$_POST["name"];
$u_password=$_POST["password"];
$u_contact=$_POST["contact"]";
$u_country=$_POST["country"];
$sql_query="insert into users values('$u_name', '$u_password', '$u_contact', '$u_country');";
//mysqli_query($connection, $sql_query));
if(mysqli_query($connection,$sql_query))
{
//echo "data inserted";
}
else{
//echo "error";
}
?>
And also the init.php :
<?php
$db_name = "project";
$mysql_user = "root";
$server_name = "localhost";
$connection = mysqli_connect($server_name, $mysql_user, "", $db_name);
if(!$connection){
echo "Connection not successful";
}
else{
echo "Connection successful";
}
?>
Thank you for your help !
My class PutUtility for getData(), PostData, DeleteData(). you just need to change package name
package fourever.amaze.mics;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class PutUtility {
private Map<String, String> params = new HashMap<>();
private static HttpURLConnection httpConnection;
private static BufferedReader reader;
private static String Content;
private StringBuffer sb1;
private StringBuffer response;
public void setParams(Map<String, String> params) {
this.params = params;
}
public void setParam(String key, String value) {
params.put(key, value);
}
public String getData(String Url) {
StringBuilder sb = new StringBuilder();
try {
// Defined URL where to send data
URL url = new URL(Url);
URLConnection conn = null;
conn = url.openConnection();
// Send POST data request
httpConnection = (HttpURLConnection) conn;
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(
new InputStreamReader(httpConnection.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) { }
}
return response.toString();
}
public String postData(String Url) {
StringBuilder sb = new StringBuilder();
for (String key : params.keySet()) {
String value = null;
value = params.get(key);
if (sb.length() > 0) {
sb.append("&");
}
sb.append(key + "=" + value);
}
try {
// Defined URL where to send data
URL url = new URL(Url);
URLConnection conn = null;
conn = url.openConnection();
// Send POST data request
httpConnection = (HttpURLConnection) conn;
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestMethod("POST");
httpConnection.setDoInput(true);
httpConnection.setDoOutput(true);
OutputStreamWriter wr = null;
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(sb.toString());
wr.flush();
BufferedReader in = new BufferedReader(
new InputStreamReader(httpConnection.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
return response.toString();
}
public String putData(String Url) {
StringBuilder sb = new StringBuilder();
for (String key : params.keySet()) {
String value = null;
try {
value = URLEncoder.encode(params.get(key), "UTF-8");
if (value.contains("+"))
value = value.replace("+", "%20");
//return sb.toString();
// Get the server response
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (sb.length() > 0) {
sb.append("&");
}
sb.append(key + "=" + value);
}
try {
// Defined URL where to send data
URL url = new URL(Url);
URLConnection conn = null;
conn = url.openConnection();
// Send PUT data request
httpConnection = (HttpURLConnection) conn;
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestMethod("PUT");
httpConnection.setDoInput(true);
httpConnection.setDoOutput(false);
OutputStreamWriter wr = null;
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(sb.toString());
wr.flush();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
;
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb1.append(line + " ");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
// Send PUT data request
return Url;
}
public String deleteData(String Url) {
StringBuilder sb = new StringBuilder();
for (String key : params.keySet()) {
try {
// Defined URL where to send data
URL url = new URL(Url);
URLConnection conn = null;
conn = url.openConnection();
// Send POST data request
httpConnection = (HttpURLConnection) conn;
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestMethod("DELETE");
httpConnection.connect();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb1.append(line + " ");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
}
return Url;
}
}
And use this class like this
#Override
protected String doInBackground(String... params) {
res = null;
PutUtility put = new PutUtility();
put.setParam("ueid", params[0]);
put.setParam("firm_no", params[1]);
put.setParam("date_incorporation", params[2]);
put.setParam("business_name", params[3]);
put.setParam("block_no", params[4]);
try {
res = put.postData(
"Api URL here");
Log.v("res", res);
} catch (Exception objEx) {
objEx.printStackTrace();
}
return res;
}
#Override
protected void onPostExecute(String res) {
try {
} catch (Exception objEx) {
mProgressDialog.dismiss();
objEx.printStackTrace();
}
}
Please use this. Hope it helps you in future also.
Check this if this is the problem
$u_contact=$_POST["contact"]"
here is the problem i think so brother. replace with
$u_contact=$_POST["contact"];
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 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();
}
}
}