下面列出了怎么用android.net.Uri.Builder的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Generates an auth endpoint with the specified parameters.
*
* @param userToken The lftoken representing a user.
* @param collectionId The Id of the collection to auth against.
* @param articleId The Id of the collection's article.
* @param siteId The Id of the article's site.
* @return The auth endpoint with the specified parameters.
* @throws UnsupportedEncodingException
* @throws MalformedURLException
*/
public static String generateAuthEndpoint(String userToken,
String collectionId,
String articleId,
String siteId) throws UnsupportedEncodingException {
Builder uriBuilder = new Uri.Builder()
.scheme(LivefyreConfig.scheme)
.authority(LivefyreConfig.adminDomain + "." + LivefyreConfig.getConfiguredNetworkID())
.appendPath("api")
.appendPath("v3.0")
.appendPath("auth")
.appendPath("");
if (collectionId != null) {
uriBuilder.appendQueryParameter("collectionId", collectionId)
.appendQueryParameter("lftoken", userToken);
} else {
final String article64 = Helpers.generateBase64String(articleId);
uriBuilder.appendQueryParameter("siteId", siteId)
.appendQueryParameter("articleId", article64)
.appendQueryParameter("lftoken", userToken);
}
Log.d("Admin URL", "" + uriBuilder.toString());
return uriBuilder.toString();
}
private void confirmDeleteThread(final String from) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.confirm_dialog_title)
.setIcon(android.R.drawable.ic_dialog_alert)
.setCancelable(true)
.setPositiveButton(R.string.delete, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(TextUtils.isEmpty(from)) {
getActivity().getContentResolver().delete(SipMessage.MESSAGE_URI, null, null);
}else {
Builder threadUriBuilder = SipMessage.THREAD_ID_URI_BASE.buildUpon();
threadUriBuilder.appendEncodedPath(from);
getActivity().getContentResolver().delete(threadUriBuilder.build(), null, null);
}
}
})
.setNegativeButton(R.string.no, null)
.setMessage(TextUtils.isEmpty(from)
? R.string.confirm_delete_all_conversations
: R.string.confirm_delete_conversation)
.show();
}
private Uri buildNewUri(Uri uri, String targetAuthority) {
Builder b = new Builder();
b.scheme(uri.getScheme());
b.authority(targetAuthority);
b.path(uri.getPath());
if (VERSION.SDK_INT >= 11) {
Set<String> names = uri.getQueryParameterNames();
if (names != null && names.size() > 0) {
for (String name : names) {
if (!TextUtils.equals(name, ApkConstant.EXTRA_TARGET_AUTHORITY)) {
b.appendQueryParameter(name, uri.getQueryParameter(name));
}
}
}
} else {
b.query(uri.getQuery());
}
b.fragment(uri.getFragment());
return b.build();
}
/**
* @param action
* @param contentId
* @param collectionId The Id of the collection.
* @param userToken The token of the logged in user.
* @param parameters
* @param networkID Livefyre provided network name
* @param handler Response handler
* @throws MalformedURLException
*/
public static void featureMessage(String action, String contentId,
String collectionId, String userToken,
HashMap<String, Object> parameters, String networkID, JsonHttpResponseHandler handler)
throws MalformedURLException {
RequestParams bodyParams = new RequestParams();
bodyParams.put("lftoken", userToken);
final Builder uriBuilder = new Uri.Builder().scheme(LivefyreConfig.scheme)
.authority(LivefyreConfig.quillDomain + "." + networkID)
.appendPath("api").appendPath("v3.0").appendPath("collection")
.appendPath(collectionId).appendPath(action)
.appendPath(contentId).appendPath("")
.appendQueryParameter("lftoken", userToken)
.appendQueryParameter("collection_id", collectionId);
Log.d("SDK", "" + uriBuilder);
HttpClient.client.post(uriBuilder.toString(), bodyParams, handler);
}
public static boolean setEmptyPassphrase(Context ctx, boolean noCreate) {
String pkey = "";
Uri uri = Provider.CONTENT_URI_WITH_ACCOUNT;
Builder builder = uri.buildUpon().appendQueryParameter(ImApp.CACHEWORD_PASSWORD_KEY, pkey);
if (noCreate) {
builder.appendQueryParameter(ImApp.NO_CREATE_KEY, "1");
}
uri = builder.build();
Cursor cursor = ctx.getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
cursor.close();
return true;
}
return false;
}
/**
* @param action
* @param contentId
* @param collectionId The Id of the collection.
* @param userToken The token of the logged in user.
* @param parameters
* @param handler Response handler
* @throws MalformedURLException
*/
public static void featureMessage(String action, String contentId,
String collectionId, String userToken,
HashMap<String, Object> parameters, JsonHttpResponseHandler handler)
throws MalformedURLException {
RequestParams bodyParams = new RequestParams();
bodyParams.put("lftoken", userToken);
final Builder uriBuilder = new Uri.Builder().scheme(LivefyreConfig.scheme)
.authority(LivefyreConfig.quillDomain + "." + LivefyreConfig.getConfiguredNetworkID())
.appendPath("api").appendPath("v3.0").appendPath("collection")
.appendPath(collectionId).appendPath(action)
.appendPath(contentId).appendPath("")
.appendQueryParameter("lftoken", userToken)
.appendQueryParameter("collection_id", collectionId);
Log.d("SDK", "" + uriBuilder);
HttpClient.client.post(uriBuilder.toString(), bodyParams, handler);
}
/**
* @param collectionId The Id of the collection.
* @param contentId
* @param token The token of the logged in user.
* @param action
* @param parameters
* @param handler Response handler
*/
public static void flagContent(String collectionId, String contentId,
String token, LFSFlag action, RequestParams parameters,
JsonHttpResponseHandler handler) {
String url = (new Uri.Builder().scheme(LivefyreConfig.scheme)
.authority(LivefyreConfig.quillDomain + "." + LivefyreConfig.getConfiguredNetworkID())
.appendPath("api").appendPath("v3.0").appendPath("message").appendPath("")) +
contentId + (new Uri.Builder().appendPath("").appendPath("flag")
.appendPath(flags[action.value()])
.appendQueryParameter("lftoken", token)
.appendQueryParameter("collection_id", collectionId));
Log.d("Action SDK call", "" + url);
Log.d("Action SDK call", "" + parameters);
HttpClient.client.post(url, parameters, handler);
}
public static boolean messageExists (ContentResolver resolver, String id)
{
boolean result = false;
Uri.Builder builder = Messages.OTR_MESSAGES_CONTENT_URI_BY_PACKET_ID.buildUpon();
builder.appendPath(id);
Cursor c = resolver.query(builder.build(),null, null, null, null);
if (c != null)
{
if (c.getCount() > 0)
result = true;
c.close();
}
return result;
}
private Uri buildNewUri(Uri uri, String targetAuthority) {
Uri.Builder b = new Builder();
b.scheme(uri.getScheme());
b.authority(targetAuthority);
b.path(uri.getPath());
if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) {
Set<String> names = uri.getQueryParameterNames();
if (names != null && names.size() > 0) {
for (String name : names) {
if (!TextUtils.equals(name, Env.EXTRA_TARGET_AUTHORITY)) {
b.appendQueryParameter(name, uri.getQueryParameter(name));
}
}
}
} else {
b.query(uri.getQuery());
}
b.fragment(uri.getFragment());
return b.build();
}
/**
* @param collectionId The Id of the collection.
* @param contentId
* @param token The token of the logged in user.
* @param action
* @param parameters
* @param handler Response handler
*/
public static void postAction(String collectionId, String contentId,
String token, LFSActions action, RequestParams parameters,
JsonHttpResponseHandler handler) {
// Build the URL
String url = new Uri.Builder().scheme(LivefyreConfig.scheme)
.authority(LivefyreConfig.quillDomain + "." + LivefyreConfig.getConfiguredNetworkID())
.appendPath("api").appendPath("v3.0").appendPath("message").appendPath("") + contentId +
(new Uri.Builder().appendPath(actions[action.value()]).appendPath("")
.appendQueryParameter("lftoken", token)
.appendQueryParameter("collection_id", collectionId));
Log.d("Action SDK call", "" + url);
Log.d("Action SDK call", "" + parameters);
HttpClient.client.post(url, parameters, handler);
}
public static int updateConfirmInDb(ContentResolver resolver, long threadId, String msgId, boolean isDelivered) {
Uri.Builder builder = Imps.Messages.OTR_MESSAGES_CONTENT_URI_BY_PACKET_ID.buildUpon();
builder.appendPath(msgId);
ContentValues values = new ContentValues(1);
values.put(Imps.Messages.IS_DELIVERED, isDelivered);
values.put(Messages.THREAD_ID,threadId);
int result = resolver.update(builder.build(), values, null, null);
if (result == 0)
{
builder = Messages.CONTENT_URI_MESSAGES_BY_PACKET_ID.buildUpon();
builder.appendPath(msgId);
result = resolver.update(builder.build(), values, null, null);
}
return result;
}
public Uri getUriForFile(File file) {
try {
String rootPath;
String path = file.getCanonicalPath();
Entry<String, File> mostSpecific = null;
for (Entry<String, File> root : this.mRoots.entrySet()) {
rootPath = ((File) root.getValue()).getPath();
if (path.startsWith(rootPath) && (mostSpecific == null || rootPath.length() > ((File) mostSpecific.getValue()).getPath().length())) {
mostSpecific = root;
}
}
if (mostSpecific == null) {
throw new IllegalArgumentException("Failed to find configured root that contains " + path);
}
rootPath = ((File) mostSpecific.getValue()).getPath();
if (rootPath.endsWith("/")) {
path = path.substring(rootPath.length());
} else {
path = path.substring(rootPath.length() + 1);
}
return new Builder().scheme(WidgetRequestParam.REQ_PARAM_COMMENT_CONTENT).authority(this.mAuthority).encodedPath(Uri.encode((String) mostSpecific.getKey()) + LetvUtils.CHARACTER_BACKSLASH + Uri.encode(path, "/")).build();
} catch (IOException e) {
throw new IllegalArgumentException("Failed to resolve canonical path for " + file);
}
}
public static int updateMessageInDb(ContentResolver resolver, String id, int type, long time, long contactId) {
Uri.Builder builder = Imps.Messages.OTR_MESSAGES_CONTENT_URI_BY_PACKET_ID.buildUpon();
builder.appendPath(id);
ContentValues values = new ContentValues(2);
values.put(Imps.Messages.TYPE, type);
values.put(Imps.Messages.THREAD_ID, contactId);
if (time != -1)
values.put(Imps.Messages.DATE, time);
int result = resolver.update(builder.build(), values, null, null);
if (result == 0)
{
builder = Imps.Messages.CONTENT_URI_MESSAGES_BY_PACKET_ID.buildUpon();
builder.appendPath(id);
result = resolver.update(builder.build(), values, null, null);
}
return result;
}
void insertBlockedContactToDataBase(Contact contact) {
// Remove the blocked contact if it already exists, to avoid duplicates and
// handle the odd case where a blocked contact's nickname has changed
removeBlockedContactFromDataBase(contact);
Uri.Builder builder = Imps.BlockedList.CONTENT_URI.buildUpon();
ContentUris.appendId(builder, mConn.getProviderId());
ContentUris.appendId(builder, mConn.getAccountId());
Uri uri = builder.build();
String username = mAdaptee.normalizeAddress(contact.getAddress().getAddress());
ContentValues values = new ContentValues(2);
values.put(Imps.BlockedList.USERNAME, username);
values.put(Imps.BlockedList.NICKNAME, contact.getName());
mResolver.insert(uri, values);
mValidatedBlockedContacts.add(username);
}
public static String login(String username, String pass) throws Exception {
getInitCookies(ig);
URLConnection connection = new URL(igAuth).openConnection();
if(connection instanceof HttpURLConnection){
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
httpURLConnection.setRequestMethod(HttpPost.METHOD_NAME);
httpURLConnection = addPostHeaders(httpURLConnection);
String query = new Builder().appendQueryParameter("username", username).appendQueryParameter("password", pass).build().getEncodedQuery();
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, HTTP.UTF_8));
bufferedWriter.write(query);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
httpURLConnection.connect();
if(httpURLConnection.getResponseCode() != HttpStatus.SC_OK){
return "bad_request";
}
extractAndSetCookies(httpURLConnection);
JSONObject jsonObject = new JSONObject(buildResultString(httpURLConnection));
if(jsonObject.get("user").toString().isEmpty()){
return BuildConfig.VERSION_NAME;
}
return jsonObject.get("authenticated").toString();
}
throw new IOException("Url is not valid");
}
/**
* @param collectionId The Id of the collection.
* @param userToken The token of the logged in user.
* @param endpoint
* @return
* @throws MalformedURLException
*/
public static String generateWriteURL(
String collectionId, String userToken, String endpoint)
throws MalformedURLException {
final Builder uriBuilder = new Uri.Builder().scheme(LivefyreConfig.scheme)
.authority(LivefyreConfig.quillDomain + "." + LivefyreConfig.getConfiguredNetworkID())
.appendPath("api").appendPath("v3.0").appendPath("collection")
.appendPath(collectionId).appendPath("post");
if (LFSConstants.LFSPostTypeReview == endpoint)
uriBuilder.appendPath(endpoint).appendPath("");
else
uriBuilder.appendPath("");
Log.d("Write URL", "" + uriBuilder.toString());
return uriBuilder.toString();
}
public static Uri.Builder uriBuilder(@NonNull final Uri baseUri,
@NonNull final String... newPathSegments) {
final Builder builder = baseUri.buildUpon();
for (final String path : newPathSegments) {
builder.appendEncodedPath(path);
}
return builder;
}
/**
* Generates a general bootstrap endpoint with the specified parameters.
*
* @param siteId The Id of the article's site.
* @param articleId The Id of the collection's article.
* @param opts Optional parameters to pass in. Currently takes in pageNumber param for Bootstrap page number.
* @return The init endpoint with the specified parameters.
* @throws UnsupportedEncodingException
* @throws MalformedURLException
*/
public static String generateBootstrapEndpoint(String siteId,String articleId,Map<String, Object>... opts)throws UnsupportedEncodingException {
// Casting
final String article64 = Helpers.generateBase64String(articleId);
// Build the URL
Builder uriBuilder = new Uri.Builder()
.scheme(LivefyreConfig.scheme)
.authority(LivefyreConfig.bootstrapDomain + "." + LivefyreConfig.getConfiguredNetworkID())
.appendPath("bs3")
.appendPath("v3.1")
.appendPath(LivefyreConfig.getConfiguredNetworkID())
.appendPath(siteId)
.appendPath(article64);
if (opts.length <= 0) {
uriBuilder.appendPath("init");
} else {
if (opts[0].get("pageNumber") instanceof Integer) {
String page = opts[0].get("pageNumber").toString() + ".json";
uriBuilder.appendPath(page);
} else {
throw new IllegalArgumentException("Bootstrap page number must be an Integer");
}
}
return uriBuilder.toString();
}
public HTTPAgent buildLogin(String account, String password, String appId) {
Builder ub = getBuilder("uac/m/login");
HTTPAgent.Builder hb = new HTTPAgent.Builder();
append(hb, "account", account);
append(hb, "pwd", password);
append(hb, "appid", appId);
return new PostAgent(ub.build(), Passport.getHosts(), hb.buildJSON());
}
public HTTPAgent buildRelogin(String uid, String password, String appId) {
Builder ub = getBuilder("uac/m/relogin");
HTTPAgent.Builder hb = new HTTPAgent.Builder();
append(hb, "uid", uid);
append(hb, "pwd", password);
append(hb, "appid", appId);
return new PostAgent(ub.build(), Passport.getHosts(), hb.buildJSON());
}
public PostAgent buildCheckPassword(String uid, String account, String password, String appId) {
Builder ub = getBuilder("uac/m/check_pwd");
HTTPAgent.Builder hb = new HTTPAgent.Builder();
append(hb, "uid", uid);
append(hb, "account", account);
append(hb, "pwd", password);
append(hb, "appid", appId);
return new PostAgent(ub.build(), Passport.getHosts(), hb.buildJSON());
}
public PostAgent buildCheckTKT(String uid, String account, String tkt, String appId) {
Builder ub = getBuilder("uac/m/check_tkt");
HTTPAgent.Builder hb = new HTTPAgent.Builder();
append(hb, "uid", uid);
append(hb, "account", account);
append(hb, "tkt", tkt);
append(hb, "appid", appId);
return new PostAgent(ub.build(), Passport.getHosts(), hb.buildJSON());
}
public PostAgent buildCheckTKT(String openid, String access_token, String appId) {
Builder ub = getBuilder("uac/m/oauth2/authenticate");
HTTPAgent.Builder hb = new HTTPAgent.Builder();
append(hb, "openid", openid);
append(hb, "access_token", access_token);
append(hb, "appid", appId);
return new PostAgent(ub.build(), Passport.getHosts(), hb.buildJSON());
}
public PostAgent buildLogout(String uid, String tkt, String password, String appId) {
Builder ub = getBuilder("uac/m/logout");
HTTPAgent.Builder hb = new HTTPAgent.Builder();
append(hb, "uid", uid);
append(hb, "tkt", tkt);
append(hb, "pwd", password);
append(hb, "appid", appId);
return new PostAgent(ub.build(), Passport.getHosts(), hb.buildJSON());
}
public HTTPAgent buildRegisterPhoneGetActivateCode(String phone, String appId) {
Builder ub = getBuilder("uac/m/register/phone/get_activate_code");
HTTPAgent.Builder hb = new HTTPAgent.Builder();
append(hb, "phone", phone);
append(hb, "appid", appId);
return new PostAgent(ub.build(), Passport.getHosts(), hb.buildJSON());
}
public HTTPAgent buildRegisterPhone(String phone, String code, String password, String nickname, String appId) {
Builder ub = getBuilder("uac/m/register/phone/register");
HTTPAgent.Builder hb = new HTTPAgent.Builder();
append(hb, "activate_code", code);
append(hb, "phone", phone);
append(hb, "pwd", password);
append(hb, "nickname", nickname);
append(hb, "appid", appId);
return new PostAgent(ub.build(), Passport.getHosts(), hb.buildJSON());
}
public HTTPAgent buildRegisterEmail(String email, String password, String nickname, String appId) {
Builder ub = getBuilder("uac/m/register/email/get_link");
HTTPAgent.Builder hb = new HTTPAgent.Builder();
append(hb, NotificationCompat.CATEGORY_EMAIL, email);
append(hb, "pwd", password);
append(hb, "nickname", nickname);
append(hb, "appid", appId);
return new PostAgent(ub.build(), Passport.getHosts(), hb.buildJSON());
}
public HTTPAgent buildCheckPresentOnActivate(String ccid, String imsi, String appId) {
Builder ub = getBuilder("uac/m/activate/check_present");
append(ub, "ccid", ccid);
append(ub, "imsi", imsi);
append(ub, "appid", appId);
return new GetAgent(ub.build(), Passport.getHosts());
}
public static int deleteMessageInDb(ContentResolver resolver, String id) {
Uri.Builder builder = Messages.OTR_MESSAGES_CONTENT_URI_BY_PACKET_ID.buildUpon();
builder.appendPath(id);
int result = resolver.delete(builder.build(), null, null);
if (result <= 0)
{
builder = Imps.Messages.CONTENT_URI_MESSAGES_BY_PACKET_ID.buildUpon();
builder.appendPath(id);
result = resolver.delete(builder.build(), null, null);
}
return result;
}
public HTTPAgent buildForwardPhoneGetActivateCode(String phone, String appId) {
Builder ub = getBuilder("uac/m/forward/phone/get_activate_code");
HTTPAgent.Builder hb = new HTTPAgent.Builder();
append(hb, "phone", phone);
append(hb, "appid", appId);
return new PostAgent(ub.build(), Passport.getHosts(), hb.buildJSON());
}