I'm writing an Android app that connects to a SOAP webservice using kSOAP2, and I have a kXML element where I would like to inject a child based on an XML string I got from elsewhere (a REST API). I have the following code:
Element samlHeader = new Element().createElement("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security");
samlHeader.setPrefix("wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
samlHeader.setPrefix("wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
String samlTokenString = ...; //I got this from elsewhere
Element samlTokenElement = ...; //I don't know how to build this
samlHeader.addChild(Node.ELEMENT, samlTokenElement);
So I'm trying to figure out how to build my Element based on the XML string I'm getting from elsewhere.
This is the solution that we ended up implementing:
try {
KXmlParser parser = new KXmlParser();
parser.setInput(new StringReader(samlTokenString));
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
Document samlTokenDocument = new Document();
samlTokenDocument.parse(parser);
samlHeader.addChild(Node.ELEMENT, samlTokenDocument.getRootElement());
} catch (XmlPullParserException e) {
Log.e(TAG,"Could not parse SAML assertion", e);
} catch (IOException e) {
Log.e(TAG,"Could not parse SAML assertion", e);
}
We're still validating if it produces the right result but it seems to work.
Related
This code returns nothing when I'm trying to scrap data from airbnb,
try {
doc = Jsoup.connect("https://www.airbnb.com").
header("Accept", "text/html")
.header("Accept-Encoding", "gzip,deflate")
.header("Accept-Language", "it-IT,en;q=0.8,en-US;q=0.6,de;q=0.4,it;q=0.2,es;q=0.2")
.header("Connection", "keep-alive")
.userAgent("Mozilla")
.get();
} catch (IOException e) {
e.printStackTrace();
}
Elements els = doc.getElementsByClass("cy5jw6o dir dir-ltr");
System.out.println(els);
I tried the mentioned code and also this
Elements els = doc.getElementsByClass("div.cy5jw6o.dir.dir-ltr");
How to get all elements with this class name and even access links under it or other divs under?
I want to send an JSONObject using retrofit 2 to server and i am sending this kind of json object :
{"Order Summary":
"[
{
\ "ProductName\":\"Wine\",
\"ProductPrice\":\"500\",
\"ProductQuantity\":\"2\",
\"ProductCost\":\"1000\",
\"SellerId\":\"2\"
},
{
\"ProductName\":\"Whiskey\",
\"ProductPrice\":\"1000\",
\"ProductQuantity\":\"1\",
\"ProductCost\":\"1000\",
\"SellerId\":\"1\"
}
]"}
due to which i'm unable to parse the json object
and this is the source code iam using :-
private void loadCart()
{
Cursor cursor = dbHelper.getCarProducts();
cursor.moveToFirst();
do {
JSONObject product = new JSONObject();
try {
product.put("Sellerid",cursor.getString(cursor.getColumnIndex("_Sellerid")));
product.put("ProductCost",cursor.getString(cursor.getColumnIndex("_Cost")));
product.put("ProductQuantity",cursor.getString(cursor.getColumnIndex("_Quantity")));
product.put("ProductPrice",cursor.getString(cursor.getColumnIndex("_Price")));
product.put("ProductName",cursor.getString(cursor.getColumnIndex("_Name")));
userCart.put(product);
} catch (JSONException e) {
e.printStackTrace();
}
}while(cursor.moveToNext());
Cart = new JSONObject();
try
{
Cart.put("OrderSummary",userCart.toString());
}
catch (Exception ex)
{}}
could someone tell me how to rectify this error ?
Here is your mistake
Cart.put("OrderSummary", userCart.toString());
You get pure JSON Array but why are you converting it to String?
Use,
Cart.put("OrderSummary", userCart); // remove .toString()
Edit
By checking your server side code, I think the problem is in index.php file (I'm not expert in PHP)
$requestedData = $response->getBody();
Instead of $response you should use $request object. In order to fix that refer this StackOverflow thread or refer this official doc of Slim Framework.
And to send JSON response from Slim Framework to refer this StackOverflow thread.
Note: While declaring Java variables/objects try to respect Java varibales/method naming conventions. Instead of Cart use cart, this eliminates ambiguity.
I'm building hybrid applications that rely on 2-way communication between javascript in a webview and the hosting application.
Attitudes differ somewhat as in IOS the JS can send a message to swift (using WKWebView), that listens through
userContentController(userContentController: WKUserContentController,
didReceiveScriptMessage message: WKScriptMessage)
when implementing the WKScriptMessageHandler protocol,
whereas in Android the JS can actually call an Android method that has #JavascriptInterface annotation, after calling addJavascriptInterface().
Both approaches are OK for me, as I'm passing around data using JSON strings. Question is, what if I need to pass a media file, say an image or video, from the web page to the application? should I just pass a bitmap inside the json? Seems a little naive... recommendations?
edit: when passing an image from the application to the webpage I save the file to the file system and send the filename to the webview. Can it be done the other way around? Can javascript save to the hosting mobile device file system?
You have to host(in case of webapp) or store(in case of mobile app) the image and pass the image url, not exactly the image.
Almost all api that uses images bitmap also takes image url.
regards
Ashish
To answer your second question which is there are comments, use the following code.
Here the html content is your binary content:
FileWriter imageFileWriter = null;
BufferedWriter imageBufferedWriter = null;
ABOUtil.createDir(InMemoryDataStructure.FILE_PATH.getFileDirForimage());
File imageFileDir = new File(InMemoryDataStructure.FILE_PATH.getFileDirForimage());
String imageName = "/finalimage"+ filename + jpg
File mimageFile = new File(imageFileDir, imageName);
try {
imageFileWriter = new FileWriter(mimageFile, false);
imageBufferedWriter = new BufferedWriter(imageFileWriter);
StringBuilder sb = new StringBuilder();
sb.append(htmlContent);
sb.append(scriptInjectJavascript(lstimageNameValue));
imageBufferedWriter.write(sb.toString());
imageBufferedWriter.close();
return mimageFile;
}
catch (IOException e) {
MAFLogger.e("", "", e);
}
finally{
if(imageFileWriter!=null)
try {
imageFileWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
MAFLogger.e("","",e);
}
if(imageBufferedWriter!=null)
try {
imageBufferedWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
MAFLogger.e("","",e);
}
}
I have an issue on Android 4.1.2 where a JSON object given to us by our REST API gets encoded weirdly when sending back.
This is the snippet of json I'm getting:
"cost":{
"amount": 0,
"currency": "GBP"
}
I'm wanting to pretty much just pass this particular snippet back the same way (modifying other parts of the json), but this is what I get on Android 4.1.2:
"cost":"{amount=0, currency=GBP}"
The function I believe is causing this weird encoding is here:
private StringEntity getEntityForRequest(final Payment payment, final PaymentDelegate delegate) {
JSONObject json = new JSONObject();
MyApplication.getContext().addApplicationInformationToJSONObject(json);
StringEntity entity = null;
try {
entity = new StringEntity(json.toString(), "UTF-8");
} catch (UnsupportedEncodingException e1) {
payment.markAsFailed("Reservation failed, data returned not expected.");
save(payment);
if (delegate != null) {
delegate.onFailure(new MyError(MyError.DEFAULT_STATUS, MyError.DEFAULT_TYPE, "Payment error", "Error during reservation"));
}
}
return entity;
}
This is the addApplicationIformationToJSONObject function:
/**
* Adds system information to a JSON object.
*/
public void addApplicationInformationToJSONObject(JSONObject json) {
try {
try {
json.put("app_version", getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
} catch (NameNotFoundException e) {
json.put("app_version", "Unknown");
}
json.put("device", getDeviceName());
json.put("os_type", "android");
json.put("os_version", String.format("%d", Build.VERSION.SDK_INT));
json.put("device_id", Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID));
} catch (JSONException e) {
MyLog.e("MyApplication", "Error when adding system information to JSON");
}
}
What's causing this weird encoding?
How can I modify the code to avoid issues like this?
Found a solution. It seems older version interprets that cost snippet as a string rather than a JSONObject. Doing this seems to solve the issue:
ticketObject.remove("cost");
ticketObject.put("cost", new JSONObject(getCost()));
I am very new to Android Development and Java,
I have C# experience
anyway
I am trying to get XML from a URL
I tried every possible thing but non is working.
Always get crash or no result.
I just want a simple XML result, I found some JSON and PHP code, that i do not want to connect to MySQL.
is there any simple function to retrieve the XML as string from a URL
this is one of my traials
`
lbl1 = (TextView) findViewById(R.id.lbl1);
try {
InputStream is = new URL("http://api.androidhive.info/pizza/?format=xml").openConnection().getInputStream();
String strxml = is.toString();
lbl1.setText(strxml);
}
catch (MalformedURLException e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
}
catch (IOException e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
}`
any help will be much appreciated. Thanks
How would you do it in C#?
URL.toString() and (in c#) Request.Url.ToString() are alike. Both behave the same way: creating a string of the URL.
(Like in C#) you would need a HTTP client: http://android-developers.blogspot.de/2011/09/androids-http-clients.html