I would like to parse a string such as p1=6&p2=7&p3=8 into a NameValueCollection.
What is the most elegant way of doing this when you don't have access to the Page.Request object?
There's a built-in .NET utility for this: HttpUtility.ParseQueryString
// C#
NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring);
' VB.NET
Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(querystring)
You may need to replace querystring with new Uri(fullUrl).Query.
HttpUtility.ParseQueryString will work as long as you are in a web app or don't mind including a dependency on System.Web. Another way to do this is:
NameValueCollection queryParameters = new NameValueCollection();
string[] querySegments = queryString.Split('&');
foreach(string segment in querySegments)
{
string[] parts = segment.Split('=');
if (parts.Length > 0)
{
string key = parts[0].Trim(new char[] { '?', ' ' });
string val = parts[1].Trim();
queryParameters.Add(key, val);
}
}
A lot of the answers are providing custom examples because of the accepted answer's dependency on System.Web. From the Microsoft.AspNet.WebApi.Client NuGet package there is a UriExtensions.ParseQueryString, method that can also be used:
var uri = new Uri("https://stackoverflow.com/a/22167748?p1=6&p2=7&p3=8");
NameValueCollection query = uri.ParseQueryString();
So if you want to avoid the System.Web dependency and don't want to roll your own, this is a good option.
I wanted to remove the dependency on System.Web so that I could parse the query string of a ClickOnce deployment, while having the prerequisites limited to the "Client-only Framework Subset".
I liked rp's answer. I added some additional logic.
public static NameValueCollection ParseQueryString(string s)
{
NameValueCollection nvc = new NameValueCollection();
// remove anything other than query string from url
if(s.Contains("?"))
{
s = s.Substring(s.IndexOf('?') + 1);
}
foreach (string vp in Regex.Split(s, "&"))
{
string[] singlePair = Regex.Split(vp, "=");
if (singlePair.Length == 2)
{
nvc.Add(singlePair[0], singlePair[1]);
}
else
{
// only one key with no value specified in query string
nvc.Add(singlePair[0], string.Empty);
}
}
return nvc;
}
To do this without System.Web, without writing it yourself, and without additional NuGet packages:
Add a reference to System.Net.Http.Formatting
Add using System.Net.Http;
Use this code:
new Uri(uri).ParseQueryString()
https://msdn.microsoft.com/en-us/library/system.net.http.uriextensions(v=vs.118).aspx
I needed a function that is a little more versatile than what was provided already when working with OLSC queries.
Values may contain multiple equal signs
Decode encoded characters in both name and value
Capable of running on Client Framework
Capable of running on Mobile Framework.
Here is my solution:
Public Shared Function ParseQueryString(ByVal uri As Uri) As System.Collections.Specialized.NameValueCollection
Dim result = New System.Collections.Specialized.NameValueCollection(4)
Dim query = uri.Query
If Not String.IsNullOrEmpty(query) Then
Dim pairs = query.Substring(1).Split("&"c)
For Each pair In pairs
Dim parts = pair.Split({"="c}, 2)
Dim name = System.Uri.UnescapeDataString(parts(0))
Dim value = If(parts.Length = 1, String.Empty,
System.Uri.UnescapeDataString(parts(1)))
result.Add(name, value)
Next
End If
Return result
End Function
It may not be a bad idea to tack <Extension()> on that too to add the capability to Uri itself.
If you don't want the System.Web dependency, just paste this source code from HttpUtility class.
I just whipped this together from the source code of Mono. It contains the HttpUtility and all it's dependencies (like IHtmlString, Helpers, HttpEncoder, HttpQSCollection).
Then use HttpUtility.ParseQueryString.
https://gist.github.com/bjorn-ali-goransson/b04a7c44808bb2de8cca3fc9a3762f9c
If you want to avoid the dependency on System.Web that is required to use HttpUtility.ParseQueryString, you could use the Uri extension method ParseQueryString found in System.Net.Http.
Make sure to add a reference (if you haven't already) to System.Net.Http in your project.
Note that you have to convert the response body to a valid Uri so that ParseQueryString (in System.Net.Http)works.
string body = "value1=randomvalue1&value2=randomValue2";
// "http://localhost/query?" is added to the string "body" in order to create a valid Uri.
string urlBody = "http://localhost/query?" + body;
NameValueCollection coll = new Uri(urlBody).ParseQueryString();
I just realized that Web API Client has a ParseQueryString extension method that works on a Uri and returns a HttpValueCollection:
var parameters = uri.ParseQueryString();
string foo = parameters["foo"];
private void button1_Click( object sender, EventArgs e )
{
string s = #"p1=6&p2=7&p3=8";
NameValueCollection nvc = new NameValueCollection();
foreach ( string vp in Regex.Split( s, "&" ) )
{
string[] singlePair = Regex.Split( vp, "=" );
if ( singlePair.Length == 2 )
{
nvc.Add( singlePair[ 0 ], singlePair[ 1 ] );
}
}
}
Just access Request.QueryString. AllKeys mentioned as another answer just gets you an array of keys.
HttpUtility.ParseQueryString(Request.Url.Query) return is HttpValueCollection (internal class). It inherits from NameValueCollection.
var qs = HttpUtility.ParseQueryString(Request.Url.Query);
qs.Remove("foo");
string url = "~/Default.aspx";
if (qs.Count > 0)
url = url + "?" + qs.ToString();
Response.Redirect(url);
Since everyone seems to be pasting his solution.. here's mine :-)
I needed this from within a class library without System.Web to fetch id parameters from stored hyperlinks.
Thought I'd share because I find this solution faster and better looking.
public static class Statics
public static Dictionary<string, string> QueryParse(string url)
{
Dictionary<string, string> qDict = new Dictionary<string, string>();
foreach (string qPair in url.Substring(url.IndexOf('?') + 1).Split('&'))
{
string[] qVal = qPair.Split('=');
qDict.Add(qVal[0], Uri.UnescapeDataString(qVal[1]));
}
return qDict;
}
public static string QueryGet(string url, string param)
{
var qDict = QueryParse(url);
return qDict[param];
}
}
Usage:
Statics.QueryGet(url, "id")
Hit up Request.QueryString.Keys for a NameValueCollection of all query string parameters.
To get all Querystring values try this:
Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(querystring)
Dim sb As New StringBuilder("<br />")
For Each s As String In qscoll.AllKeys
Response.Write(s & " - " & qscoll(s) & "<br />")
Next s
var q = Request.QueryString;
NameValueCollection qscoll = HttpUtility.ParseQueryString(q.ToString());
I translate to C# version of josh-brown in VB
private System.Collections.Specialized.NameValueCollection ParseQueryString(Uri uri)
{
var result = new System.Collections.Specialized.NameValueCollection(4);
var query = uri.Query;
if (!String.IsNullOrEmpty(query))
{
var pairs = query.Substring(1).Split("&".ToCharArray());
foreach (var pair in pairs)
{
var parts = pair.Split("=".ToCharArray(), 2);
var name = System.Uri.UnescapeDataString(parts[0]);
var value = (parts.Length == 1) ? String.Empty : System.Uri.UnescapeDataString(parts[1]);
result.Add(name, value);
}
}
return result;
}
let search = window.location.search;
console.log(search);
let qString = search.substring(1);
while(qString.indexOf("+") !== -1)
qString = qString.replace("+", "");
let qArray = qString.split("&");
let values = [];
for(let i = 0; i < qArray.length; i++){
let pos = qArray[i].search("=");
let keyVal = qArray[i].substring(0, pos);
let dataVal = qArray[i].substring(pos + 1);
dataVal = decodeURIComponent(dataVal);
values[keyVal] = dataVal;
}
This is my code, I think it's very useful:
public String GetQueryString(string ItemToRemoveOrInsert = null, string InsertValue = null )
{
System.Collections.Specialized.NameValueCollection filtered = new System.Collections.Specialized.NameValueCollection(Request.QueryString);
if (ItemToRemoveOrInsert != null)
{
filtered.Remove(ItemToRemoveOrInsert);
if (!string.IsNullOrWhiteSpace(InsertValue))
{
filtered.Add(ItemToRemoveOrInsert, InsertValue);
}
}
string StrQr = string.Join("&", filtered.AllKeys.Select(key => key + "=" + filtered[key]).ToArray());
if (!string.IsNullOrWhiteSpace(StrQr)){
StrQr="?" + StrQr;
}
return StrQr;
}
Related
I have existing PHP that accepts arrays as parameters. This is currently being invoked from javascript and the javascript array is being set directly as part of the data object sent through AJAX call to the php.
Now, I want to send an array from an Android app and I don't want to change the existing php and javascript. I have looked for an answer, but don't see anything, other than the suggestion to encode the array as JSON and decode it in the php, but that will require lots of changes everywhere, including the javascript. It appears the javascript and the php are made to just work. Maybe something is done automatically to the array?
The PHP looks like this:
foreach($_POST as $key => $value) {
if (is_array($_POST[$key])){
for ($index = 0; $index < count($_POST[$key]); $index++){
if(ini_get('magic_quotes_gpc'))
$_POST[$key][$index] = stripslashes($_POST[$key][$index]);
$_POST[$key][$index] = htmlspecialchars(strip_tags($_POST[$key][$index]));
}
}
else {
if(ini_get('magic_quotes_gpc'))
$_POST[$key] = stripslashes($_POST[$key]);
$_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}
}
So, it is definitely expecting some parameters to be arrays.
The javascript currently does this:
$.ajax({
type: "POST",
url: 'php/getLibraryPatterns.php',
dataType: 'json',
data: data,
and data is a javascript object with arrays contained in it. For example:
var data = {};
if (sortBy.length > 0){
data.sortBy = sortBy;
}
and sortBy is an array in the javascript.
How do I pass an array from the Android app to this php? Currently, all of the parameters for my other calls to php have just been simple strings, so I use the following function to put all the parameters together in a string and then write that to the OutputStream of my HttpURLConnection. I have that all working, just not sure what to do with the arrays?
private String buildParameterString() throws UnsupportedEncodingException
{
if (m_parameterMap == null) return "";
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<Map.Entry<String, String>> itr = m_parameterMap.entrySet().iterator();
while(itr.hasNext())
{
Map.Entry<String, String> param = itr.next();
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(param.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(param.getValue(), "UTF-8"));
}
return result.toString();
}
I tried creating a JSONArray with the data, then convert to string and set it just like I would set the other strings I am sending. But, this does not appear to work, at least not automagically.
So, I am sending something like "[29]" or "['sortAsc']" as strings in the parameters.
I got back an empty list. I will continue to debug in the php to see what those look like there, but I expect they will be just strings and the php won't know what to do with that.
So, how can I send an array to the php? I don't want to have to change the php, as that means that the javascript then also has to change. Is there any way to do this from a java Android app?
Solution Found!
I found an answer in the JQuery documentation for ajax method. It says there that arrays are encoded like this:
%5B is '['
and %5D is ']'
For example, { a: [1,2] } becomes the string "a%5B%5D=1&a%5B%5D=2" with the default traditional: false setting.
I have encoded my arrays like that in the string that I write to the output stream. From https://api.jquery.com/jQuery.ajax/
Here is the code I am using to create my output stream:
private String buildParameterString() throws UnsupportedEncodingException
{
if (m_parameterMap == null || m_parameterMap.size() == 0) return "";
StringBuilder result = new StringBuilder();
for (int iPair = 0; iPair < m_parameterMap.size(); iPair++)
{
Pair<String, Object> param = m_parameterMap.get(iPair);
if (iPair > 0) result.append("&");
Object value = param.second;
if (value instanceof ArrayList){
for (int i = 0; i < ((ArrayList)value).size(); i++){
Object nextValue = ((ArrayList)value).get(i);
String nextValueStr = "";
if (nextValue instanceof String){
nextValueStr = (String)nextValue;
}
else {
nextValueStr = Integer.toString((Integer)nextValue);
}
if (i > 0) result.append("&");
result.append(URLEncoder.encode(param.first, "UTF-8"));
result.append("%5B%5D=");
result.append(URLEncoder.encode(nextValueStr, "UTF-8"));
}
}
else {
result.append(URLEncoder.encode(param.first, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode((String)value, "UTF-8"));
}
}
return result.toString();
}
m_parameters is an ArrayList of Pair's where Pair is in android.util.
It works, this is the answer. You don't have to encode and decode in JSON string to do this. All the othere answers I have seen for this are just that. There is a way to encode the array into the string output.
Try this:
Outside of while loop:
JSONArray data = new JSONArray();
And put this in while loop:
JSONObject jsonObjSend = new JSONObject();
jsonObjSend.put(param.getKey(), param.getValue());
data.put(jsonObjSend);
From Android, send it as json data
public String convertMapToJson() {
Map<String, String> elements = new HashMap<>();
elements.put("Key1", "Value1");
elements.put("Key2", "Value2");
elements.put("Key3", "Value3");
JSONObject json = new JSONObject(elements);
return json.toString();
}
In server side PHP,
$json = file_get_contents('php://input');
// Converts it into a PHP object
$params = json_decode($json, true);
echo $params["Key1"];
I'm trying to Verifying that requests originate from Office for the web by using proof keys
I have read this resource many times but still do not know how to implement it in PHP.
I tried the code below it didn't seem to solve the problem, I do not know what to do next.
Can someone give me a suggestion?
$rsa = new Crypt_RSA();
$modulus = new Math_BigInteger(base64_decode($modulus), 256);
$exponent = new Math_BigInteger(base64_decode($exponent), 256);
$rsa->loadKey(array('n' => $modulus, 'e' => $exponent));
$rsa->setPublicKey();
$publicKey = $rsa->getPublicKey();
I understand that verifying WOPI proof key is quite complicated to implement while extracting programming logic from their explanation in the document is challenging.
Unfortunately, I'm not a PHP developer. However, I'd like to share my production C# code in case it could help.
private async Task<bool> ValidateWopiProof(HttpContext context)
{
// Make sure the request has the correct headers
if (!context.Request.Headers.ContainsKey(WopiRequestHeader.PROOF) ||
!context.Request.Headers.ContainsKey(WopiRequestHeader.TIME_STAMP))
return false;
// TimestampOlderThan20Min
var timeStamp = long.Parse(context.Request.Headers[WopiRequestHeader.TIME_STAMP].ToString());
var timeStampDateTime = new DateTime(timeStamp, DateTimeKind.Utc);
if ((DateTime.UtcNow - timeStampDateTime).TotalMinutes > 20)
return false;
// Set the requested proof values
var requestProof = context.Request.Headers[WopiRequestHeader.PROOF];
var requestProofOld = String.Empty;
if (context.Request.Headers.ContainsKey(WopiRequestHeader.PROOF_OLD))
requestProofOld = context.Request.Headers[WopiRequestHeader.PROOF_OLD];
// Get the WOPI proof info from Wopi discovery
var wopiProofPublicKey = await _wopiDiscovery.GetWopiProof();
// Encode the values into bytes
var accessTokenBytes = Encoding.UTF8.GetBytes(context.Request.Query["access_token"].ToString());
var hostUrl = GetAbsolouteUrl(context);
var hostUrlBytes = Encoding.UTF8.GetBytes(hostUrl.ToUpperInvariant());
var timeStampBytes = BitConverter.GetBytes(Convert.ToInt64(context.Request.Headers[WopiRequestHeader.TIME_STAMP])).Reverse().ToArray();
// Build expected proof
List<byte> expected = new List<byte>(
4 + accessTokenBytes.Length +
4 + hostUrlBytes.Length +
4 + timeStampBytes.Length);
// Add the values to the expected variable
expected.AddRange(BitConverter.GetBytes(accessTokenBytes.Length).Reverse().ToArray());
expected.AddRange(accessTokenBytes);
expected.AddRange(BitConverter.GetBytes(hostUrlBytes.Length).Reverse().ToArray());
expected.AddRange(hostUrlBytes);
expected.AddRange(BitConverter.GetBytes(timeStampBytes.Length).Reverse().ToArray());
expected.AddRange(timeStampBytes);
byte[] expectedBytes = expected.ToArray();
return (VerifyProofKeys(expectedBytes, requestProof, wopiProofPublicKey.Value) ||
VerifyProofKeys(expectedBytes, requestProofOld, wopiProofPublicKey.Value) ||
VerifyProofKeys(expectedBytes, requestProof, wopiProofPublicKey.OldValue));
}
private string GetAbsolouteUrl(HttpContext context)
{
var url = $"{_wopiUrlService.ApiAddress.TrimEnd('/')}{context.Request.Path}{context.Request.QueryString}";
return url.Replace(":44300", "").Replace(":443", "");
}
private bool VerifyProofKeys(byte[] expectedProof, string proofFromRequest, string discoPublicKey)
{
using (RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider())
{
try
{
rsaProvider.ImportCspBlob(Convert.FromBase64String(discoPublicKey));
return rsaProvider.VerifyData(expectedProof, "SHA256", Convert.FromBase64String(proofFromRequest));
}
catch (FormatException)
{
return false;
}
catch (CryptographicException)
{
return false;
}
}
}
This implementation follows the document spec. For the method _wopiDiscovery.GetWopiProof(), I just get proof-key section from Wopi Discovery.
.
#Rachanee is your solution working? I have the same code but validation is failing.
You can find a WOPI Proof Validator in PHP, in this package: https://github.com/Champs-Libres/wopi-lib/
This package is a helper for integrating WOPI protocol in PHP applications.
It contains a WOPI Proof Validator service that you can use out of the box.
I am trying to fetch some data from server using json in my flutter app. This is the function I am using.
List<String> userFriendList = ["No Friends"];
Future<http.Response> _fetchSampleData() {
return http.get('//link/to/server/fetcher/test_fetcher.php');
}
Future<void> getDataFromServer() async {
final response = await _fetchSampleData();
if (response.statusCode == 200) {
Map<String, dynamic> data = json.decode(response.body);
userLvl = data["lvl"].toString();
userName = data["name"];
userFriendList = List();
userFriendList = data["friendlist"];
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
print('Failed to load data from server');
}
}
I get the usrLvl and userName right. But for userFriendList, I get the following error:
[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<String>'
Code on the server end (test_fetcher.php) :
<?php
$myObj->name = "JohnDoe";
$myObj->lvl = 24;
$friends = array("KumarVishant", "DadaMuni", "BabuBhatt", "BesuraGayak", "BabluKaneria", "MorrisAbhishek", "GoodLuckBaba", "ViratKohli", "LeanderPaes");
$myObj->friendlist = $friends;
header('Content-Type: application/json');
$myJSON = json_encode($myObj);
echo $myJSON;
?>
This is a cast error: List<dynamic> != List<String>
You can convert / cast your list in several ways.
I advise you to use this library to simplify your json / Dart object conversion
: https://pub.dev/packages/json_serializable
json_serializable will generate the conversion methods (fromJson and toJson) and take care of everything.
It's easier and safer than doing it manually.
Just what the error says. The userFriendList is of type List you have it as List.
List<String> userFriendList = ["No Friends"];
Should be
List<dynamic> userFriendList = [];
Or a different list entirely if this doesn't work for you.
The error explains it. The fetched data from the server api is decoded to type List<dynamic> and you declared userFriendList to be of type List<String>. What you need to do is change the type of userFriendList from
List<String> userFriendList = ["No Friends"];
to:
List<dynamic> userFriendList = [];
I am writing a Native Android App in which i am using PHP MYSQL to get data from server
In this [Appointment List] i am allowing user to Reschedule an Appointment, but whenever i do tap on item getting blank form, in short not getting data for that particular appointment which i have clicked in a List.
Question
How to show data in a form using AppointmentID ?
Below i am showing all required code written by me [Client & Server Side both]
UpcomingActivity.java:
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
int menuItemIndex = item.getItemId();
String[] menuItems = Cmd;
String CmdName = menuItems[menuItemIndex];
// Check Event Command
if ("Cancel".equals(CmdName))
{
Toast.makeText(UpcomingActivity.this,"Selected Cancel",Toast.LENGTH_LONG).show();
}
else if ("Reschedule".equals(CmdName))
{
Toast.makeText(UpcomingActivity.this,"Selected Update",Toast.LENGTH_LONG).show();
String sAppointmentID = MyArrList.get(info.position).get("UserID").toString();
Log.d(tag, "sAppointmentID :: " + sAppointmentID);
Intent newActivity = new Intent(UpcomingActivity.this, UpdateActivity.class);
newActivity.putExtra("UserID", sAppointmentID);
startActivity(newActivity);
}
return true;
}
UpdateActivity.java:
public void showInfo()
{
final TextView tAppointmentID = (TextView)findViewById(R.id.txtUsername);
final TextView tType = (TextView)findViewById(R.id.txtName);
final TextView tDate = (TextView)findViewById(R.id.txtEmail);
final TextView tTime = (TextView)findViewById(R.id.txtTel);
Button btnSave = (Button) findViewById(R.id.btnSave);
Button btnCancel = (Button) findViewById(R.id.btnCancel);
String url = "http://10.0.2.2/appointments/getByMemberID.php";
Intent intent= getIntent();
final String AppointmentID = intent.getStringExtra("AppointmentID");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sAppointmentID", AppointmentID));
String resultServer = getHttpPost(url,params);
String strAppointmentID = "";
String strType = "";
String strDate = "";
String strTime = "";
JSONObject c;
try {
c = new JSONObject(resultServer);
strAppointmentID = c.getString("UserID");
Log.d(TAG, "String strAppointmentID" + strAppointmentID);
strType = c.getString("Type");
Log.d(TAG, "String strType" + strType);
strDate = c.getString("Date");
Log.d(TAG, "String strDate" + strDate);
strTime = c.getString("Time");
Log.d(TAG, "String strTime" + strTime);
if(!strAppointmentID.equals(""))
{
tAppointmentID.setText(strAppointmentID);
tType.setText(strType);
tDate.setText(strDate);
tTime.setText(strTime);
}
else
{
tAppointmentID.setText("-");
tType.setText("-");
tDate.setText("-");
tTime.setText("-");
btnSave.setEnabled(false);
btnCancel.requestFocus();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
first of all make sure that you have valid AppointmentID and UserIdand
in UpcomingActivity.java at method onContextItemSelected you are not providing AppointmentID instead you are only providing UserID to the Intend
List but in Updateactivity at method showData you are requesting intent.getStringExtra("AppointmentID") which is invaild.
so your update your UpcomingActivity.java should look like this
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
int menuItemIndex = item.getItemId();
String[] menuItems = Cmd;
String CmdName = menuItems[menuItemIndex];
// Check Event Command
if ("Cancel".equals(CmdName))
{
Toast.makeText(UpcomingActivity.this,"Selected Cancel",Toast.LENGTH_LONG).show();
}
else if ("Reschedule".equals(CmdName))
{
Toast.makeText(UpcomingActivity.this,"Selected Update",Toast.LENGTH_LONG).show();
String sAppointmentID = MyArrList.get(info.position).get("UserID").toString();
Log.d(tag, "sAppointmentID :: " + sAppointmentID);
Intent newActivity = new Intent(UpcomingActivity.this, UpdateActivity.class);
newActivity.putExtra("UserID", sAppointmentID);
newActivity.putExtra("AppointmentID", MyArrList.get(info.position).get("AppointmentID").toString());// <== here
startActivity(newActivity);
}
return true;
}
I noticed a couple of issues (might be typos, but I prefer to ask anyway):
You are calling a getByMemberID.php, but you have not included its source code in the question - you do have such service, right? :)
In the onContextItemSelected you are starting the UpdateActivity and pass UserID as extra. But in the showInfo method of that activity you are trying to get AppointmentID from the intent's extras, so it is not processing any data.
1) Try weather your PHP code is working fine or not...
You can do that by running directly on server and passing UserId and appoinmentId as a parameter by ?
For eg.... www.abc.com?sUserId=123?sAppointmentID=456
See weather it's showing you proper output.
2) you are calling getByMemberID.php but you have specified code of it but you are not passing "AppointmentID" for that also check with php code weather you are retriving it ??
3) On call of updateData.php in UpdateActivity.java: you are not providing "AppointmentID" but you are retriving it in php code it will get null value by default which will be an error ofcourse
I have created and Android app that has to communicate with my website using JSON. JSON (on client, Android side) looks like this:
private static String JSONSend(Context ctx, JSONObject obj, String ObjName, String address) {
IHttpDispatcher disp = new HttpDispatcher();
Vector<String> ss = new Vector<String>();
String link = address;
String locale = uzmiLocale(ctx);
if(locale=="")
return "";
try {
obj.put("Lokal", locale);
ss.add(ObjName + obj.toString());
String ID = disp.getHttpResponse_POST(link, ss);
return ID;
} catch (Exception e) {
return "";
}
}
Above method is called from here:
public static String sendReq(Context ctx, String txt, String number) {
JSONObject jsn = new JSONObject();
try {
jsn.put("TextPoruke", txt);
jsn.put("BrTel", number);
return JSONSend(ctx, jsn, "JSNSend=", "www.mysite.com");
} catch (JSONException e1) {
return "";
}
}
Everything works fine on my Wamp server, but after moving my php code to webserver, nightmare started! Apparently, everything is sent the way it should be, but on serverside this php code is creating problems:
if(isset ($_POST['JSNSend']))
{
$argument = $_POST['JSNSend'];
$json = json_decode($argument,true);
$broj = $json['BrTel'];
$jsnLocale = $json['Lokal'];
it seems that result of "json_decode" is NULL, but $argument equals
{"\TextPoruke\": \"sometext\", \"BrTel\":\"111\"}
So passed JSON string seems ok, but for some reason it can't be decoded on webserver. Can anyone help me with this? Why is it not working?
Seems like your JSON got escaped prematurely which triggers a bad syntax error.
If $argument is in the format you state, then the following procedure would work:
<?php
$s = '{"\TextPoruke\": \"sometext\", \"BrTel\":\"111\"}';
echo 'Without stripslashes:' . PHP_EOL;
var_dump( json_decode( $s ) );
echo 'With stripslashes:' . PHP_EOL;
var_dump( json_decode( stripslashes($s) ) );
?>
Result:
Without stripslashes:
NULL
With stripslashes:
object(stdClass)#1 (2) {
["TextPoruke"]=>
string(8) "sometext"
["BrTel"]=>
string(3) "111"
}
Disable magic_quotes_gpc. This was a completely misguided ‘security’ feature that should never be used. It runs addslashes() on all user input, with the premise that this would solve SQL-injection problems (it doesn't).
If the server isn't yours and so you can't disable it, use the “Disabling magic quotes at runtime” hack on that link for now and consider moving to a new host.