I have a Android app that needs to launch a web brower with a URL containing a query string. I build my Uri like this:
Uri uri = builder.scheme("https")
.authority("ids.example.com")
.appendPath("account")
.appendPath("login")
.appendQueryParameter("client_id", "seglaren")
.appendQueryParameter("scope", "openid email name")
.build();
and pass it to the browser using:
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
This launches the browser with the following URL:
https://ids.example.com/account/login?client_id=seglaren&scope=openid%20email%20name
The problem here is that the server I am calling does not accept this URL: it requires the separator between the query parameters to be encoded to "%26" instead of just "&". So it would need to be:
https://ids.example.com/account/login?client_id=seglaren%26scope=openid%20email%20name
How do I fix this?
Instead of .appendQueryParameter() you can use .encodedQuery().
encodedQuery() will be treated as if it is already encoded, thus not encoding it again. So you may insert your own string as you wish like in the example below.
String params = "client_id=seglaren%26scope=openid%20email%20name";
Uri uri = new Uri.Builder().scheme("https")
.authority("ids.artdatabanken.se")
.appendPath("account")
.appendPath("login")
.encodedQuery(params)
.build();
You may use string concatenation or a StringBuilder to make the String params dynamic if you don't want to keep it hardcoded.
Result
"https://ids.artdatabanken.se/account/login?client_id=seglaren%26scope=openid%20email%20name"
Note that androids Uri.Builder is doing the correct thing by adding &to the parameter. So the API you're using probably has a bug if it requires %26.
I am constructing String in my android app and then pass it to URLEncoder.
String searchStr;
// then I get some searchStr from shared preferences
// i check it is correct
searchStr = searchStr + "/page/"+pageNumber+"";
Then I pass that searchStr to URL encoder:
try {
String url_params = URLEncoder.encode(params[0]);
String result = downloadURL("some url/" + url_params);
Log.d("key", url_params); // -> php/page/10
}catch (IOException){
Log.d("key", e.getMessage() );
}
So here i get IOException which shows me this message:
http://some url/php%2Fpage%2F10
If I copy paste it to browser it shows me Not found error with this message:
The requested url someurl/php/page/10 was not found on this server
Also if I change those strange sign %2F into / in browser I am able to get the page. So how can I construct proper string with / instead of %2F sign?
You don't encode the entire URL, only parts of it that come from "unreliable sources".
String query = URLEncoder.encode("apples oranges", "utf-8");
String url = "http://stackoverflow.com/search?q=" + query;
I am sagar, i am trying to implement the Parse Push-Notification in android using REST API (Service), and i am almost got success in implement the Push-Notification in Xamarin-Android using REST API. But i got stuck with one part in sending the Data into REST service. I trying to pass the ParseObject in service, but the in parse table there is a need of Object,(). I have tried to pass the ParseObject as below:
JsonConvert.SerializeObject(ParseUser.CurrentUser)
It convert ParseObject into array and array is not accepted in table and ,i got failed to save it in table. because there i a need of object.
I need solution or suggestion from developer guys. Yours help will be appreciated. I am trying the below code to achieve the result.
public static void RegisterPush(string regristrationId)
{
if (regristrationId != null) {
string appID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string restID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string masterID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
try {
var client = new RestClient ("https://api.parse.com");
var request = new RestRequest ("1/installations", RestSharp.Method.POST);
request.AddHeader ("Accept", "application/json");
request.AddHeader ("X-Parse-Application-Id", appID);
request.AddHeader ("X-Parse-REST-API-Key", restID);
request.Credentials = new NetworkCredential (appID, masterID);
request.Parameters.Clear ();
Console.Error.WriteLine ("ParseUser.CurrentUser-->"+ (ParseObject) ParseUser.CurrentUser);
//JsonConvert.SerializeObject(ParseUser.CurrentUser)
string strJSONContent = "{\"user\" :"+ JsonConvert.SerializeObject(ParseUser.CurrentUser)+",\"owner\":\"" + ParseUser.CurrentUser.ObjectId + "\",\"deviceType\":\"android\",\"GCMSenderId\":\"1234567890\",\"appName\":\"abcdefgh\",\"pushType\":\"gcm\",\"deviceToken\":\"" + regristrationId + "\"}";
Console.Error.WriteLine("json string-->"+ strJSONContent);
request.AddParameter ("application/json", strJSONContent, ParameterType.RequestBody);
client.ExecuteAsync (request, response => {
Console.Error.WriteLine ("response for android parse installation-->" + response.Content);
});
} catch (Exception ex) {
Console.WriteLine (ex.Message);
}
}
}`
Output:{"user" :[{"Key":"dealOffered","Value":4},{"Key":"dealRequested","Value":5},{"Key":"displayName","Value":"Cook"},{"Key":"email","Value":"lorenzo#gmail.com"},{"Key":"firstName","Value":"Lorenzo"},{"Key":"lastName","Value":"Cook"},{"Key":"mobileNumber","Value":9999999999.0},{"Key":"picture","Value":{"IsDirty":false,"Name":"tfss-afd25c29-6679-4843-842c-fe01f7fcf976-profile.jpg","MimeType":"image/jpeg","Url":"http://files.parsetfss.com/profile.jpg"}},{"Key":"provider","Value":"password"},{"Key":"userType","Value":"Merchant"},{"Key":"username","Value":"merchant#sailfish.com"},{"Key":"zipCode","Value":2342343}],"owner":"3cF1vHUXkW","deviceType":"android","GCMSenderId":"1234567890123","appName":"Sailfish","pushType":"gcm","deviceToken":"APA91bE3bsTIInQcoloOBE4kdLVVHVTRVtNyA1A788hYSC15wAVu8mUg-lwk7ZPk370rngrK7J6OoLmiM9HRr1CGPaBo6LCNrSUL7erBku4vepaFFkQzgqS6BcAemp"}
Error:{"code":111,"error":"invalid type for key user, expected *_User, but got array"}
maven
I found the solution in , parse xamarin docs, in one query , the way is simple, but i little bit hard to found out.
The issue is with the data passing in json format in REST, to pass any pointer using REST API, use as below.
The solution is as below:
`{
"user":{
"__type":"Pointer",
"className":"_User",
"objectId":"qYvzFzGAzc"
},
"owner":"qYvzFzGAzc",
"deviceType":"android",
"GCMSenderId":"123456789",
"appName":"NiceApp",
"pushType":"gcm",
"deviceToken":"APA91bFeM10jdrCS6fHqGGSkON17UjEJEfvJEmGpRM-d6hq3hQgDxKHbyrqAIxMnEGgbLEZf0E9AllHxiQQQCdEFiNMF1_A8q0n9tGpBE5NKhvS2ZGJ9PZ7585puWqz_1Z1EjSjOvgZ1LQo708DeL2KzA7EFJmdPAA"
}`
It looks like your column user is set up wrong. It should show as a Pointer<_User> not Pointer
If you load this class in your Data Browser, is the "user" key defined as a string, or a Pointer <_User>
This error seems to indicate that this is a string column, which is why the Parse.User object is not being accepted as a valid value. You might have tried setting a string on this key before, which in turn type-locked the "user" key as a string column.
Found it on the examples given on this page - https://www.parse.com/docs/rest
Have you check your REST API connection while passing ParseObject?
Because your error says:
Error:{"code":111,"error":"invalid type for key user, expected *_User, but got array"}
Here "code":111This error code comes when server refuse for connection
I am trying to communicate with Facebook doing simple things. At the moment I can log a user in and post to their wall as them. But for whatever reason, I can't seem to access public information such as their name. I consistently get this error:
{"error":{"message":"Syntax error \"Expected end of string instead of \"?\".\" at character 4: name?access_token=MYACCESSTOKEN","type":"OAuthException","code":2500}}
Here is the call:
SampleRequestListener srl = new SampleRequestListener();
AsyncFacebookRunner afr = new AsyncFacebookRunner(facebook);
afr.request("http://graph.facebook.com/me?fields=name", (RequestListener)srl);
That call is made within a validated session (in the onComplete portion of the DialogListener for .Authorize). Using my access_token and the exact same string as above I can get the request to work just fine at http://developers.facebook.com/tools/explorer/
The error occurs whilst parsing the response in the RequestListener.onComplete
JSONObject json = Util.parseJson(response);
final String name = json.getString("name");
System.out.println("Hi, my name is " + name);
Thank you for your time. All input is welcomed.
UPDATE *
There are two things going on. In the facebook API, Util.openUrl was appending a "?" between the field name and the access_token (as the answer below pointed out). This seems odd. I wonder if I pulled an old version of the API or something. You would think that would be set up correctly.
Also, I called the method incorrectly:
This:
afr.request("http://graph.facebook.com/me?fields=name", (RequestListener)srl);
Should be:
afr.request("me?fields=name", (RequestListener)srl);
If you are using com.facebook.Request class then just use the following form of constructor: Request(Session session, String graphPath, Bundle parameters, HttpMethod httpMethod, Callback callback) and pass your parameters in "parameters" parameter.
Just like:
if (GlobalApplication.accessToken != null && !GlobalApplication.accessToken.isExpired()) {
/* make the API call */
Bundle b = new Bundle();
b.putString("fields", "id,created_time,description,embed_html,name,source,picture");
new GraphRequest(GlobalApplication.accessToken, "/me/videos",
b, HttpMethod.GET, new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
/* handle the result */
Log.i("", "");
String string = response.toString();
JSONObject object = response.getJSONObject();
JSONArray array = response.getJSONArray();
Log.i("", "");
}
}).executeAsync();
Looks like the actual request being sent is something like
/me?fields=name?access_token=MYACCESSTOKEN
and that of course is wrong; it should be an ampersand before the second parameter and not a question mark.
You’d have to look for the location in the code where the access token is added as parameter. At that point there should be a check for whether this URL already contains a question mark or not before appending the access_token parameter.
When I try to shorten a link with "#,&" character I get an exception. Is there a way to handle these character properly?
This is a sample code that works:
String shortUrl = bitly.getShortUrl("http://z"); //Works
If I add for example '&' or '%25' to the string it will throw an exception:
String shortUrl = bitly.getShortUrl("http://z%26"); // Exception
String shortUrl = bitly.getShortUrl("http://z&"); // Exception
The getShortUrl function from this Java class.
Thanks
That library (the Java class you link to) doesn't escape the URL... that's pretty awful.
Excerpt:
private String getBitlyHttpResponseText(String urlToShorten) throws IOException {
String uri = getBitlyUrl() + urlToShorten + bitlyAuth;
HttpGet httpGet = new HttpGet(uri);
...
Notice how urlToShorten isn't escaped in any way, shape or form. Prone to injection-style attacks, and just generally doesn't work.
Anyway, you'll need to escape urlToShorten.