Java 类com.squareup.okhttp.HttpUrl 实例源码

项目:mobile-sdk-android    文件:BaseRoboTest.java   
@Before
public void setup() {
    Robolectric.getBackgroundThreadScheduler().reset();
    Robolectric.getForegroundThreadScheduler().reset();
    ShadowLog.stream = System.out;
    activity = Robolectric.buildActivity(MockMainActivity.class).create().start().resume().visible().get();
    shadowOf(activity).grantPermissions("android.permission.INTERNET");
    server= new MockWebServer();
    try {
        server.start();
        HttpUrl url= server.url("/");
        UTConstants.REQUEST_BASE_URL_UT_V2 = url.toString();
        System.out.println(UTConstants.REQUEST_BASE_URL_UT_V2);
        ShadowSettings.setTestURL(url.toString());
        TestResponsesUT.setTestURL(url.toString());
    } catch (IOException e) {
        System.out.print("IOException");
    }
    bgScheduler = Robolectric.getBackgroundThreadScheduler();
    uiScheduler = Robolectric.getForegroundThreadScheduler();
    Robolectric.flushBackgroundThreadScheduler();
    Robolectric.flushForegroundThreadScheduler();
    bgScheduler.pause();
    uiScheduler.pause();
}
项目:boohee_v5.6    文件:AuthenticatorAdapter.java   
public Request authenticate(Proxy proxy, Response response) throws IOException {
    List<Challenge> challenges = response.challenges();
    Request request = response.request();
    HttpUrl url = request.httpUrl();
    int size = challenges.size();
    for (int i = 0; i < size; i++) {
        Challenge challenge = (Challenge) challenges.get(i);
        if ("Basic".equalsIgnoreCase(challenge.getScheme())) {
            PasswordAuthentication auth = java.net.Authenticator
                    .requestPasswordAuthentication(url.host(), getConnectToInetAddress(proxy,
                            url), url.port(), url.scheme(), challenge.getRealm(), challenge
                            .getScheme(), url.url(), RequestorType.SERVER);
            if (auth != null) {
                return request.newBuilder().header("Authorization", Credentials.basic(auth
                        .getUserName(), new String(auth.getPassword()))).build();
            }
        }
    }
    return null;
}
项目:boohee_v5.6    文件:AuthenticatorAdapter.java   
public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
    List<Challenge> challenges = response.challenges();
    Request request = response.request();
    HttpUrl url = request.httpUrl();
    int size = challenges.size();
    for (int i = 0; i < size; i++) {
        Challenge challenge = (Challenge) challenges.get(i);
        if ("Basic".equalsIgnoreCase(challenge.getScheme())) {
            InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
            PasswordAuthentication auth = java.net.Authenticator
                    .requestPasswordAuthentication(proxyAddress.getHostName(),
                            getConnectToInetAddress(proxy, url), proxyAddress.getPort(), url
                                    .scheme(), challenge.getRealm(), challenge.getScheme(),
                            url.url(), RequestorType.PROXY);
            if (auth != null) {
                return request.newBuilder().header("Proxy-Authorization", Credentials.basic
                        (auth.getUserName(), new String(auth.getPassword()))).build();
            }
        }
    }
    return null;
}
项目:boohee_v5.6    文件:HttpURLConnectionImpl.java   
public final Permission getPermission() throws IOException {
    int hostPort;
    URL url = getURL();
    String hostName = url.getHost();
    if (url.getPort() != -1) {
        hostPort = url.getPort();
    } else {
        hostPort = HttpUrl.defaultPort(url.getProtocol());
    }
    if (usingProxy()) {
        InetSocketAddress proxyAddress = (InetSocketAddress) this.client.getProxy().address();
        hostName = proxyAddress.getHostName();
        hostPort = proxyAddress.getPort();
    }
    return new SocketPermission(hostName + ":" + hostPort, "connect, resolve");
}
项目:okwallet    文件:DynamicFeeLoader.java   
public DynamicFeeLoader(final Context context) {
    super(context);
    final PackageInfo packageInfo = WalletApplication.packageInfoFromContext(context);
    final int versionNameSplit = packageInfo.versionName.indexOf('-');
    this.dynamicFeesUrl = HttpUrl.parse(Constants.DYNAMIC_FEES_URL
            + (versionNameSplit >= 0 ? packageInfo.versionName.substring(versionNameSplit) : ""));
    this.userAgent = WalletApplication.httpUserAgent(packageInfo.versionName);
    this.assets = context.getAssets();
}
项目:okwallet    文件:AlertDialogsFragment.java   
@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    backgroundThread = new HandlerThread("backgroundThread", Process.THREAD_PRIORITY_BACKGROUND);
    backgroundThread.start();
    backgroundHandler = new Handler(backgroundThread.getLooper());

    final PackageInfo packageInfo = application.packageInfo();
    final int versionNameSplit = packageInfo.versionName.indexOf('-');
    final HttpUrl.Builder url = HttpUrl
            .parse(Constants.VERSION_URL
                    + (versionNameSplit >= 0 ? packageInfo.versionName.substring(versionNameSplit) : ""))
            .newBuilder();
    url.addEncodedQueryParameter("package", packageInfo.packageName);
    url.addQueryParameter("current", Integer.toString(packageInfo.versionCode));
    versionUrl = url.build();
}
项目:nordnet-next-api    文件:TestSessionInit.java   
@Ignore("There is a problem in this test as the sessionKey gets updated by the integration tests and failing this tests.")
@Test
public void sessionInitShouldReturnSessionKey() throws IOException {
    HttpUrl baseUrl = server.url("/next/2/");

    JSONObject sessionInitRecorded = recordedResponses.sessionInit();
    server.enqueue(new MockResponse().setBody(sessionInitRecorded.toString()));

    Properties properties = resourceReader.getProperties("test.properties");
    properties.setProperty("baseurl", baseUrl.toString());

    Session session = new Session(properties);
    Login loginObject = session.getLoginObject();

    assertThat("The sessionkey from login object should match the recorded session key",
            loginObject.getSessionKey(), equalTo(sessionInitRecorded.getString("session_key")));

    assertThat("Only one request was made to the mock server",
            server.getRequestCount(), equalTo(1));
}
项目:EmarsysPredictSDKAndroid    文件:Session.java   
String generateGET(Transaction transaction) {
    // Validate merchantId
    if (merchantId == null || merchantId.isEmpty()) {
        // The merchantId is required
        throw new Error("The merchantId is required", Error.ERROR_MISSING_MERCHANT_ID, null);
    }

    HttpUrl.Builder builder = new HttpUrl.Builder()
            .scheme(secure ? "https" : "http")
            .host(SERVER)
            .addPathSegment("merchants")
            .addPathSegment(merchantId);
    // Serialize query
    transaction.serialize(builder);
    Log.d(TAG, builder.build().query());
    return builder.build().url().toString();
}
项目:Auth0.Android    文件:AuthenticationAPIClient.java   
/**
 * Requests new Credentials using a valid Refresh Token. The received token will have the same audience and scope as first requested. How the new Credentials are requested depends on the {@link Auth0#isOIDCConformant()} flag.
 * - If the instance is OIDC Conformant the endpoint will be /oauth/token with 'refresh_token' grant, and the response will include an id_token and an access_token if 'openid' scope was requested when the refresh_token was obtained.
 * - If the instance is not OIDC Conformant the endpoint will be /delegation with 'urn:ietf:params:oauth:grant-type:jwt-bearer' grant, and the response will include an id_token.
 * Example usage:
 * <pre>
 * {@code
 * client.renewAuth("{refresh_token}")
 *      .addParameter("scope", "openid profile email")
 *      .start(new BaseCallback<Credentials>() {
 *          {@literal}Override
 *          public void onSuccess(Credentials payload) { }
 *
 *          {@literal}@Override
 *          public void onFailure(AuthenticationException error) { }
 *      });
 * }
 * </pre>
 *
 * @param refreshToken used to fetch the new Credentials.
 * @return a request to start
 */
@SuppressWarnings("WeakerAccess")
public ParameterizableRequest<Credentials, AuthenticationException> renewAuth(@NonNull String refreshToken) {
    final Map<String, Object> parameters = ParameterBuilder.newBuilder()
            .setClientId(getClientId())
            .setRefreshToken(refreshToken)
            .setGrantType(auth0.isOIDCConformant() ? ParameterBuilder.GRANT_TYPE_REFRESH_TOKEN : ParameterBuilder.GRANT_TYPE_JWT)
            .asDictionary();

    HttpUrl url;
    if (auth0.isOIDCConformant()) {
        url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder()
                .addPathSegment(OAUTH_PATH)
                .addPathSegment(TOKEN_PATH)
                .build();
    } else {
        url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder()
                .addPathSegment(DELEGATION_PATH)
                .build();
    }

    return factory.POST(url, client, gson, Credentials.class, authErrorBuilder)
            .addParameters(parameters);
}
项目:Auth0.Android    文件:Auth0.java   
private HttpUrl resolveConfiguration(@Nullable String configurationDomain, @NonNull HttpUrl domainUrl) {
    HttpUrl url = ensureValidUrl(configurationDomain);
    if (url == null) {
        final String host = domainUrl.host();
        if (host.endsWith(DOT_AUTH0_DOT_COM)) {
            String[] parts = host.split("\\.");
            if (parts.length > 3) {
                url = HttpUrl.parse("https://cdn." + parts[parts.length - 3] + DOT_AUTH0_DOT_COM);
            } else {
                url = HttpUrl.parse(AUTH0_US_CDN_URL);
            }
        } else {
            url = domainUrl;
        }
    }
    return url;
}
项目:Auth0.Android    文件:BaseRequestTest.java   
@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    HttpUrl url = HttpUrl.parse("https://auth0.com");
    parameterBuilder = ParameterBuilder.newBuilder();

    baseRequest = new BaseRequest<String, Auth0Exception>(url, client, new Gson(), adapter, errorBuilder, callback, headers, parameterBuilder) {
        @Override
        public String execute() throws Auth0Exception {
            return null;
        }

        @Override
        public void onResponse(Response response) throws IOException {

        }

        @Override
        protected Request doBuildRequest() throws RequestBodyBuildException {
            return null;
        }
    };
}
项目:Auth0.Android    文件:BaseAuthenticationRequestTest.java   
@Test
public void shouldSetRealm() throws Exception {
    HttpUrl url = HttpUrl.parse(mockAPI.getDomain())
            .newBuilder()
            .addPathSegment(OAUTH_PATH)
            .addPathSegment(TOKEN_PATH)
            .build();
    AuthenticationRequest req = createRequest(url);
    mockAPI.willReturnSuccessfulLogin();
    req.setRealm("users")
            .execute();

    final RecordedRequest request = mockAPI.takeRequest();
    Map<String, String> body = bodyFromRequest(request);
    assertThat(body, hasEntry("realm", "users"));
}
项目:Auth0.Android    文件:BaseAuthenticationRequestTest.java   
@Test
public void shouldWhiteListOAuth2ParametersOnLegacyEndpoints() throws Exception {
    HashMap<String, Object> parameters = new HashMap<>();
    parameters.put("extra", "value");
    parameters.put("realm", "users");
    HttpUrl url = HttpUrl.parse(mockAPI.getDomain())
            .newBuilder()
            .addPathSegment(OAUTH_PATH)
            .addPathSegment(RESOURCE_OWNER_PATH)
            .build();
    AuthenticationRequest req = createRequest(url);
    mockAPI.willReturnSuccessfulLogin();
    req.addAuthenticationParameters(parameters)
            .execute();

    final RecordedRequest request = mockAPI.takeRequest();
    Map<String, String> body = bodyFromRequest(request);
    assertThat(body, hasEntry("extra", "value"));
    assertThat(body, not(hasKey("realm")));
}
项目:Auth0.Android    文件:BaseAuthenticationRequestTest.java   
@Test
public void shouldWhiteListLegacyParametersOnNonLegacyEndpoints() throws Exception {
    HashMap<String, Object> parameters = new HashMap<>();
    parameters.put("extra", "value");
    parameters.put("connection", "my-connection");
    HttpUrl url = HttpUrl.parse(mockAPI.getDomain())
            .newBuilder()
            .addPathSegment(OAUTH_PATH)
            .addPathSegment(TOKEN_PATH)
            .build();
    AuthenticationRequest req = createRequest(url);
    mockAPI.willReturnSuccessfulLogin();
    req.addAuthenticationParameters(parameters)
            .execute();

    final RecordedRequest request = mockAPI.takeRequest();
    Map<String, String> body = bodyFromRequest(request);
    assertThat(body, hasEntry("extra", "value"));
    assertThat(body, not(hasKey("connection")));
}
项目:dhis2-android-dashboard    文件:LastUpdatedManager.java   
public Session get() {
    String serverUrlString = getString(SERVER_URI);
    String userNameString = getString(USERNAME);
    String passwordString = getString(PASSWORD);

    HttpUrl serverUrl = null;
    if (serverUrlString != null) {
        serverUrl = HttpUrl.parse(serverUrlString);
    }

    Credentials credentials = null;
    if (userNameString != null && passwordString != null) {
        credentials = new Credentials(
                userNameString, passwordString
        );
    }
    return new Session(serverUrl, credentials);
}
项目:dhis2-android-dashboard    文件:LastUpdatedManager.java   
public void put(Session session) {
    isNull(session, "Session object must not be null");
    HttpUrl serverUrl = session.getServerUrl();
    Credentials credentials = session.getCredentials();

    String url = null;
    String username = null;
    String password = null;

    if (serverUrl != null) {
        url = serverUrl.toString();
    }

    if (credentials != null) {
        username = credentials.getUsername();
        password = credentials.getPassword();
    }

    putString(SERVER_URI, url);
    putString(USERNAME, username);
    putString(PASSWORD, password);
}
项目:dhis2-android-dashboard    文件:UserController.java   
public UserAccount logInUser(HttpUrl serverUrl, Credentials credentials) throws APIException {
    final Map<String, String> QUERY_PARAMS = new HashMap<>();
    QUERY_PARAMS.put("fields", "id,created,lastUpdated,name,displayName," +
            "firstName,surname,gender,birthday,introduction," +
            "education,employer,interests,jobTitle,languages,email,phoneNumber," +
            "organisationUnits[id]");
    UserAccount userAccount = mDhisApi
            .getCurrentUserAccount(QUERY_PARAMS);

    // if we got here, it means http
    // request was executed successfully

    /* save user credentials */
    Session session = new Session(serverUrl, credentials);
    LastUpdatedManager.getInstance().put(session);

    /* save user account details */
    userAccount.save();

    return userAccount;
}
项目:android-step-by-step    文件:IntegrationApiModule.java   
public ApiInterface getApiInterface(MockWebServer mockWebServer) throws IOException {
    mockWebServer.start();
    TestUtils testUtils = new TestUtils();
    final Dispatcher dispatcher = new Dispatcher() {

        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {

            if (request.getPath().equals("/users/" + TestConst.TEST_OWNER + "/repos")) {
                return new MockResponse().setResponseCode(200)
                        .setBody(testUtils.readString("json/repos.json"));
            } else if (request.getPath().equals("/repos/" + TestConst.TEST_OWNER + "/" + TestConst.TEST_REPO + "/branches")) {
                return new MockResponse().setResponseCode(200)
                        .setBody(testUtils.readString("json/branches.json"));
            } else if (request.getPath().equals("/repos/" + TestConst.TEST_OWNER + "/" + TestConst.TEST_REPO + "/contributors")) {
                return new MockResponse().setResponseCode(200)
                        .setBody(testUtils.readString("json/contributors.json"));
            }
            return new MockResponse().setResponseCode(404);
        }
    };

    mockWebServer.setDispatcher(dispatcher);
    HttpUrl baseUrl = mockWebServer.url("/");
    return ApiModule.getApiInterface(baseUrl.toString());
}
项目:ecampus-client-android    文件:UserServiceTest.java   
@Before
public void setUp() throws Exception {
    super.setUp();
    server = new MockWebServer();
    server.start();
    final Dispatcher dispatcher = new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws
                InterruptedException {
            if (request.getPath().equals("/account/info")) {
                return new MockResponse().setResponseCode(200)
                        .setBody(jsonReader.readString("json/user.json"));
            }
            return new MockResponse().setResponseCode(404);
        }
    };
    server.setDispatcher(dispatcher);
    HttpUrl baseUrl = server.url("/");
    service = ServiceCreator.createTestService(baseUrl.toString(),
            UserService.class);
}
项目:JwTools    文件:OkWeb.java   
public <ResultType extends ResultAdapter>ResultType get(Class<ResultType> resultType) throws IOException, WebException {
    HttpUrl.Builder builder = HttpUrl.parse(getFullUrl()).newBuilder();
    String[] keys = getParamKeys();
    for (String key : keys) {
        builder.addEncodedQueryParameter(key, param.get(key));
    }
    HttpUrl httpUrl = builder.build();

    Request.Builder reqestBuilder = new Request.Builder().url(httpUrl);
    addHeaderAll(reqestBuilder);

    Request request = reqestBuilder.build();
    debugRequest("GET", paramString);

    clearAllParams();
    call = client.newCall(request);
    Response response = call.execute();
    ResultType result = getResult(response, resultType);
    debugResponse(result.getBody(), response);
    unexpectedCode(response, result.getBody());
    return result;
}
项目:TvEnthusiast    文件:DailyUpdateService.java   
private void initRestfulApi() {
    OkHttpClient client = new OkHttpClient();
    client.interceptors().add(chain -> {
        Request request = chain.request();
        HttpUrl url = request.httpUrl().newBuilder().addQueryParameter("api_key", BuildConfig.API_KEY).build();
        request = request.newBuilder().url(url).build();
        return chain.proceed(request);
    });

    api = new Retrofit.Builder()
            .baseUrl(BuildConfig.SERVER_URL)
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build()
            .create(RestfulApi.class);
}
项目:ProconAppAndroid    文件:AuthApi.java   
public PostNewUser post() {
    HttpUrl url = getDefaultUrlBuilder()
            .addEncodedPathSegment(PATH)
            .addEncodedPathSegment(SEGMENT)
            .build();

    RequestBody body = RequestBody.create(MEDIA_TYPE_TEXT_PLAIN, "");
    Request req = getDefaultRequestBuilder()
            .url(url)
            .post(body)
            .build();
    Timber.d("post: " + req.urlString());
    execute(req);

    if (!TextUtils.isEmpty(mResponseBodyText)) {
        Timber.d("post: code=" + mResponseStatusCode + " body=" + mResponseBodyText);
        mResponseObj = JsonUtil.fromJson(mResponseBodyText, User.class);
    }

    return this;
}
项目:ProconAppAndroid    文件:GamePhotoListApi.java   
public GetRequest get(String count) {
    HttpUrl url = getDefaultUrlBuilder()
            .addEncodedPathSegment(PATH)
            .addEncodedPathSegment(SEGMENT)
            .addEncodedQueryParameter(QUERY_COUNT, count)
            .build();

    Request req = getDefaultRequestBuilder()
            .url(url)
            .get()
            .build();
    execute(req);

    if (!TextUtils.isEmpty(mResponseBodyText)) {
        Timber.d("post: code=" + mResponseStatusCode + " body=" + mResponseBodyText);
        mResponseObj = JsonUtil.fromJson(mResponseBodyText, GamePhotoList.class);
    }

    return this;
}
项目:ProconAppAndroid    文件:NoticeDetailApi.java   
public GetRequest get(String newsId) {
    HttpUrl url = getDefaultUrlBuilder()
            .addEncodedPathSegment(PATH)
            .addEncodedPathSegment(SEGMENT)
            .addEncodedQueryParameter(QUERY_ID, newsId)
            .build();

    Request req = getDefaultRequestBuilder()
            .url(url)
            .get()
            .build();
    execute(req);

    if (!TextUtils.isEmpty(mResponseBodyText)) {
        Timber.d("post: code=" + mResponseStatusCode + " body=" + mResponseBodyText);
        mResponseObj = JsonUtil.fromJson(mResponseBodyText, NoticeDetail.class);
    }

    return this;
}
项目:ProconAppAndroid    文件:GameResultListApi.java   
/**
 * @param count       取得件数
 * @param filterQuery フィルター <code>FILTER_ALL</code> or <code>FILTER_ONLY_FOR_NOTIFICATION</code>
 * @return GetRequest
 */
public GetRequest get(String count, String filterQuery) {
    HttpUrl url = getDefaultUrlBuilder()
            .addEncodedPathSegment(PATH)
            .addEncodedPathSegment(SEGMENT)
            .addEncodedQueryParameter(QUERY_COUNT, count)
            .addEncodedQueryParameter(QUERY_FILTER, filterQuery)
            .build();

    Request req = getDefaultRequestBuilder()
            .url(url)
            .get()
            .build();
    execute(req);

    if (!TextUtils.isEmpty(mResponseBodyText)) {
        Timber.d("post: code=" + mResponseStatusCode + " body=" + mResponseBodyText);
        mResponseObj = JsonUtil.fromJson(mResponseBodyText, GameResultList.class);
    }

    return this;
}
项目:ProconAppAndroid    文件:NoticeListApi.java   
public GetRequest get(String page, String count) {
    HttpUrl url = getDefaultUrlBuilder()
            .addEncodedPathSegment(PATH)
            .addEncodedPathSegment(SEGMENT)
            .addEncodedQueryParameter(QUERY_PAGE, page)
            .addEncodedQueryParameter(QUERY_COUNT, count)
            .build();

    Request req = getDefaultRequestBuilder()
            .url(url)
            .get()
            .build();
    execute(req);

    if (!TextUtils.isEmpty(mResponseBodyText)) {
        Timber.d("post: code=" + mResponseStatusCode + " body=" + mResponseBodyText);
        mResponseObj = JsonUtil.fromJson(mResponseBodyText, NoticeList.class);
    }

    return this;
}
项目:ProconAppAndroid    文件:SocialTwitterApi.java   
public GetRequest get(String count) {
    HttpUrl url = getDefaultUrlBuilder()
            .addEncodedPathSegment(PATH)
            .addEncodedPathSegment(SEGMENT)
            .addEncodedQueryParameter(QUERY_COUNT, count)
            .build();

    Request req = getDefaultRequestBuilder()
            .url(url)
            .get()
            .build();
    execute(req);

    if (!TextUtils.isEmpty(mResponseBodyText)) {
        Timber.d("post: code=" + mResponseStatusCode + " body=" + mResponseBodyText);
        mResponseObj = JsonUtil.fromJson(mResponseBodyText, SocialFeedTwitter.class);
    }

    return this;
}
项目:ProconAppAndroid    文件:PushTokenApi.java   
public PutRequest put(String token) {
    HttpUrl url = getDefaultUrlBuilder()
            .addEncodedPathSegment(PATH)
            .addEncodedPathSegment(SEGMENT)
            .build();

    DeviceToken deviceToken = new DeviceToken(token);
    RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, JsonUtil.toJson(deviceToken));

    Request req = getDefaultRequestBuilder()
            .url(url)
            .put(body)
            .build();
    execute(req);

    if (!TextUtils.isEmpty(mResponseBodyText)) {
        Timber.d("post: code=" + mResponseStatusCode + " body=" + mResponseBodyText);
        mResponseObj = JsonUtil.fromJson(mResponseBodyText, Void.class);
    }

    return this;
}
项目:ProconAppAndroid    文件:GameNotificationApi.java   
public GetRequest get() {
    HttpUrl url = getDefaultUrlBuilder()
            .addEncodedPathSegment(PATH)
            .addEncodedPathSegment(SEGMENT)
            .build();

    Request req = getDefaultRequestBuilder()
            .url(url)
            .get()
            .build();
    execute(req);

    if (!TextUtils.isEmpty(mResponseBodyText)) {
        Timber.d("post: code=" + mResponseStatusCode + " body=" + mResponseBodyText);
        mResponseObj = JsonUtil.fromJson(mResponseBodyText, GameNotificationList.class);
    }

    return this;
}
项目:ProconAppAndroid    文件:GameNotificationApi.java   
public PutRequest put(GameNotificationList ids) {
    HttpUrl url = getDefaultUrlBuilder()
            .addEncodedPathSegment(PATH)
            .addEncodedPathSegment(SEGMENT)
            .build();

    RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, JsonUtil.toJson(ids));

    Request req = getDefaultRequestBuilder()
            .url(url)
            .put(body)
            .build();
    execute(req);

    if (!TextUtils.isEmpty(mResponseBodyText)) {
        Timber.d("post: code=" + mResponseStatusCode + " body=" + mResponseBodyText);
        mResponseObj = JsonUtil.fromJson(mResponseBodyText, Void.class);
    }

    return this;
}
项目:foursquare4j    文件:FoursquareApi.java   
/**
 * Returns tips from a user.
 * 
 * @param userId Identity of the user to get tips from. Pass self to get tips of the acting
 *        user.
 * @param limit Number of results to return, up to 200.
 * @param offset The number of results to skip. Used to page through results.
 * @param llBounds optional Restricts the returned results to the input bounding box.
 * @param categoryId optional Restricts the returned results to venues matching the input
 *        category id.
 * @param sort optional Sorts the list items. Possible values are recent and nearby. recent
 *        sorts the list items by the date added to the list. nearby sorts the list items by the
 *        distance from the center of the provided llBounds.
 * @return a List of tips
 */
public Result<List> getUserTips(String userId, Integer limit, Integer offset, 
        String llBounds, String categoryId, String sort) {
    HttpUrl.Builder urlBuilder = newApiUrlBuilder()
            .addPathSegment("lists")
            .addPathSegment(userId)
            .addPathSegment("tips");
    if (limit != null) urlBuilder.addQueryParameter("limit", String.valueOf(limit));
    if (offset != null) urlBuilder.addQueryParameter("offset", String.valueOf(offset));
    if (llBounds != null) urlBuilder.addQueryParameter("llBounds", llBounds);
    if (categoryId != null) urlBuilder.addQueryParameter("categoryId", categoryId);
    if (sort != null) urlBuilder.addQueryParameter("sort", sort);
    String json = newRequest(urlBuilder.toString());
    LOGGER.debug("Response ---> {}", json);
    return Parser.parse(json, "list", List.class);
}
项目:foursquare4j    文件:FoursquareApi.java   
/**
 * Returns a list of venues liked by the specified user.
 * 
 * @param userId User ID or self.
 * @param beforeTimestamp Seconds since epoch..
 * @param afterTimestamp Seconds since epoch.
 * @param categoryId Limits returned venues to those in this category. If specifying a top-level
 *        category, all sub-categories will also match the query.
 * @param limit Number of results to return.
 * @param offset Used to page through results.
 * @return a Group of Venues wrapped in a Result object.
 */
public Result<Group<Venue>> getUserVenueLikes(String userId, Long beforeTimestamp, 
        Long afterTimestamp, String categoryId, Integer limit, Integer offset) {
    HttpUrl.Builder urlBuilder = newApiUrlBuilder()
            .addPathSegment("users")
            .addPathSegment(userId)
            .addPathSegment("venuelikes");
    if (beforeTimestamp != null) urlBuilder.addQueryParameter("beforeTimestamp", String.valueOf(beforeTimestamp));
    if (afterTimestamp != null) urlBuilder.addQueryParameter("afterTimestamp", String.valueOf(afterTimestamp));
    if (categoryId != null) urlBuilder.addQueryParameter("categoryId", categoryId);
    if (limit != null) urlBuilder.addQueryParameter("limit", String.valueOf(limit));
    if (offset != null) urlBuilder.addQueryParameter("offset", String.valueOf(offset));
    String json = newRequest(urlBuilder.toString());
    LOGGER.debug("Response ---> {}", json);
    return Parser.parse(json, "venues", new TypeToken<Group<Venue>>(){});
}
项目:ecampus-client-android    文件:UserServiceTest.java   
@Before
public void setUp() throws Exception {
    super.setUp();
    server = new MockWebServer();
    server.start();
    final Dispatcher dispatcher = new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws
                InterruptedException {
            if (request.getPath().equals("/account/info")) {
                return new MockResponse().setResponseCode(200)
                        .setBody(jsonReader.readString("json/user.json"));
            }
            return new MockResponse().setResponseCode(404);
        }
    };
    server.setDispatcher(dispatcher);
    HttpUrl baseUrl = server.url("/");
    service = ServiceCreator.createTestService(baseUrl.toString(),
            UserService.class);
}
项目:grpc-java    文件:OkHttpClientTransport.java   
private Request createHttpProxyRequest(InetSocketAddress address, String proxyUsername,
    String proxyPassword) {
  HttpUrl tunnelUrl = new HttpUrl.Builder()
      .scheme("https")
      .host(address.getHostName())
      .port(address.getPort())
      .build();
  Request.Builder request = new Request.Builder()
      .url(tunnelUrl)
      .header("Host", tunnelUrl.host() + ":" + tunnelUrl.port())
      .header("User-Agent", userAgent);

  // If we have proxy credentials, set them right away
  if (proxyUsername != null && proxyPassword != null) {
    request.header("Proxy-Authorization", Credentials.basic(proxyUsername, proxyPassword));
  }
  return request.build();
}
项目:js-android-sdk    文件:ReportOptionRestApi.java   
/**
 * Deletes report option
 *
 * @param reportUnitUri uri of report we are deleting report option for
 * @param optionId      unique identifier that is associated with particular report option
 * @throws IOException   if socket was closed abruptly due to network issues
 * @throws HttpException if rest service encountered any status code above 300
 */
public void deleteReportOption(
        @Nullable String reportUnitUri,
        @Nullable String optionId) throws IOException, HttpException {
    Utils.checkNotNull(reportUnitUri, "Report uri should not be null");
    Utils.checkNotNull(optionId, "Option id should not be null");

    HttpUrl url = new PathResolver.Builder()
            .addPath("rest_v2")
            .addPath("reports")
            .addPaths(reportUnitUri)
            .addPath("options")
            .addPath(optionId)
            .build()
            .resolve(mNetworkClient.getBaseUrl());

    Request request = new Request.Builder()
            .addHeader("Accept", "application/json; charset=UTF-8")
            .delete()
            .url(url)
            .build();

    mNetworkClient.makeCall(request);
}
项目:js-android-sdk    文件:ReportExecutionRestApi.java   
/**
 * Initiates report execution
 *
 * @param executionOptions describes execution configuration metadata
 * @return details of execution invoked on server side
 * @throws IOException if socket was closed abruptly due to network issues
 * @throws HttpException if rest service encountered any status code above 300
 */
@NotNull
public ReportExecutionDescriptor runReportExecution(@NotNull ReportExecutionRequestOptions executionOptions) throws IOException, HttpException {
    Utils.checkNotNull(executionOptions, "Execution options should not be null");

    HttpUrl url = mNetworkClient.getBaseUrl().resolve("rest_v2/reportExecutions");

    RequestBody jsonRequestBody = mNetworkClient.createJsonRequestBody(executionOptions);
    Request request = new Request.Builder()
            .addHeader("Accept", "application/json; charset=UTF-8")
            .post(jsonRequestBody)
            .url(url)
            .build();

    com.squareup.okhttp.Response response = mNetworkClient.makeCall(request);
    return mNetworkClient.deserializeJson(response, ReportExecutionDescriptor.class);
}
项目:js-android-sdk    文件:ReportExecutionRestApi.java   
/**
 * Provides details of particular execution associated with passed id
 *
 * @param executionId unique identifier used to query details of report execution
 * @return details of requested execution invoked on server side
 * @throws IOException if socket was closed abruptly due to network issues
 * @throws HttpException if rest service encountered any status code above 300
 */
@NotNull
public ReportExecutionDescriptor requestReportExecutionDetails(@NotNull String executionId) throws IOException, HttpException {
    Utils.checkNotNull(executionId, "Execution id should not be null");

    HttpUrl url = mNetworkClient.getBaseUrl().resolve("rest_v2/reportExecutions")
            .newBuilder()
            .addPathSegment(executionId)
            .build();

    Request request = new Request.Builder()
            .addHeader("Accept", "application/json; charset=UTF-8")
            .get()
            .url(url)
            .build();

    com.squareup.okhttp.Response response = mNetworkClient.makeCall(request);
    return mNetworkClient.deserializeJson(response, ReportExecutionDescriptor.class);
}
项目:js-android-sdk    文件:ReportExecutionRestApi.java   
/**
 * Provides status of report execution
 *
 * @param executionId unique identifier used to query status of report execution
 * @return returns one of five states [execution, ready, cancelled, failed, queued]
 * @throws IOException if socket was closed abruptly due to network issues
 * @throws HttpException if rest service encountered any status code above 300
 */
@NotNull
public ExecutionStatus requestReportExecutionStatus(@NotNull String executionId) throws IOException, HttpException {
    Utils.checkNotNull(executionId, "Execution id should not be null");

    HttpUrl url = mNetworkClient.getBaseUrl()
            .resolve("rest_v2/reportExecutions")
            .newBuilder()
            .addPathSegment(executionId)
            .addPathSegment("status")
            .build();

    Request request = new Request.Builder()
            .addHeader("Accept", "application/json; charset=UTF-8")
            .get()
            .url(url)
            .build();

    com.squareup.okhttp.Response response = mNetworkClient.makeCall(request);
    return mNetworkClient.deserializeJson(response, ExecutionStatus.class);
}
项目:js-android-sdk    文件:ReportExecutionRestApi.java   
/**
 * Cancels existing report execution
 *
 * @param executionId unique identifier used to cancel report execution
 * @return flag that states whether execution cancelled or not
 * @throws IOException if socket was closed abruptly due to network issues
 * @throws HttpException if rest service encountered any status code above 300
 */
public boolean cancelReportExecution(@NotNull String executionId) throws IOException, HttpException {
    Utils.checkNotNull(executionId, "Execution id should not be null");

    HttpUrl url = mNetworkClient.getBaseUrl()
            .resolve("rest_v2/reportExecutions")
            .newBuilder()
            .addPathSegment(executionId)
            .addPathSegment("status")
            .build();

    RequestBody jsonRequestBody = mNetworkClient.createJsonRequestBody(ExecutionStatus.cancelledStatus());
    Request request = new Request.Builder()
            .addHeader("Accept", "application/json; charset=UTF-8")
            .put(jsonRequestBody)
            .url(url)
            .build();

    com.squareup.okhttp.Response response = mNetworkClient.makeCall(request);
    int status = response.code();
    return status != 204;
}
项目:js-android-sdk    文件:ReportExecutionRestApi.java   
/**
 * Updates existed report execution with new set of report parameters
 *
 * @param executionId unique identifier used to update report execution
 * @param params the key value pair association that describes parameter id and its values
 * @return flag that states whether operation updated or not
 * @throws IOException if socket was closed abruptly due to network issues
 * @throws HttpException if rest service encountered any status code above 300
 */
public boolean updateReportExecution(@NotNull String executionId,
                                     @NotNull List<ReportParameter> params) throws IOException, HttpException {
    Utils.checkNotNull(executionId, "Execution id should not be null");
    Utils.checkNotNull(params, "Execution params should not be null");
    Utils.checkArgument(params.isEmpty(), "Execution params should not be empty");


    HttpUrl url = mNetworkClient.getBaseUrl()
            .resolve("rest_v2/reportExecutions")
            .newBuilder()
            .addPathSegment(executionId)
            .addPathSegment("parameters")
            .build();

    RequestBody jsonRequestBody = mNetworkClient.createJsonRequestBody(params);
    Request request = new Request.Builder()
            .addHeader("Accept", "application/json; charset=UTF-8")
            .post(jsonRequestBody)
            .url(url)
            .build();

    com.squareup.okhttp.Response response = mNetworkClient.makeCall(request);
    int status = response.code();
    return status == 204;
}