Java Code Examples for com.squareup.okhttp.OkHttpClient

The following are top voted examples for showing how to use com.squareup.okhttp.OkHttpClient. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: owa-notifier   File: RestfullAcessProxy.java   View source code 8 votes vote down vote up
/**
 * Return a instance of tokenService to call it
 * 
 * @param authority
 * @return TokenService return a proxy to call api
 */
private static TokenService getRealTokenService(String authority) {
	// Create a logging interceptor to log request and responses
	OkHttpClient client = new OkHttpClient();
	InetSocketAddress p = findProxy();
	if(p != null) {
		client.setProxy(new Proxy(Proxy.Type.HTTP,p));
	} else { 
		client.setProxy(Proxy.NO_PROXY); 
	}
	// Create and configure the Retrofit object
	RestAdapter retrofit = new RestAdapter.Builder().setEndpoint(authority)
			.setLogLevel(LogLevel.FULL).setLog(new RestAdapter.Log() {
				@Override
				public void log(String msg) {
					logger.debug(msg);
				}
			}).setClient(new OkClient(client)).build();

	// Generate the token service
	return retrofit.create(TokenService.class);
}
 
Example 2
Project: GitHub   File: OkhttpDemoActivity.java   View source code 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.ok_http_demo_layout);
    btn_one=(Button)this.findViewById(R.id.btn_one);
    btn_two=(Button)this.findViewById(R.id.btn_two);
    top_bar_title=(TextView)this.findViewById(R.id.top_bar_title);
    tv_result=(TextView)this.findViewById(R.id.tv_result);
    top_bar_title.setText("Okhttp实例");
    top_bar_linear_back=(LinearLayout)this.findViewById(R.id.top_bar_linear_back);
    top_bar_linear_back.setOnClickListener(new CustomOnClickListener());
    btn_one.setOnClickListener(new CustomOnClickListener());
    btn_two.setOnClickListener(new CustomOnClickListener());

    client=new OkHttpClient();
}
 
Example 3
Project: GitHub   File: HttpManager.java   View source code 6 votes vote down vote up
/**
 * @param url
 * @return
 */
private OkHttpClient getHttpClient(String url) {
	Log.i(TAG, "getHttpClient  url = " + url);
	if (StringUtil.isNotEmpty(url, true) == false) {
		Log.e(TAG, "getHttpClient  StringUtil.isNotEmpty(url, true) == false >> return null;");
		return null;
	}

	OkHttpClient client = new OkHttpClient();
	client.setCookieHandler(new HttpHead());
	client.setConnectTimeout(15, TimeUnit.SECONDS);
	client.setWriteTimeout(10, TimeUnit.SECONDS);
	client.setReadTimeout(10, TimeUnit.SECONDS);
	//添加信任https证书,用于自签名,不需要可删除
	if (url.startsWith(StringUtil.URL_PREFIXs) && socketFactory != null) {
		client.setSslSocketFactory(socketFactory);
	}

	return client;
}
 
Example 4
Project: GitHub   File: HttpManager.java   View source code 6 votes vote down vote up
/**
 * @param url
 * @return
 */
private OkHttpClient getHttpClient(String url) {
	Log.i(TAG, "getHttpClient  url = " + url);
	if (StringUtil.isNotEmpty(url, true) == false) {
		Log.e(TAG, "getHttpClient  StringUtil.isNotEmpty(url, true) == false >> return null;");
		return null;
	}

	OkHttpClient client = new OkHttpClient();
	client.setCookieHandler(new HttpHead());
	client.setConnectTimeout(15, TimeUnit.SECONDS);
	client.setWriteTimeout(10, TimeUnit.SECONDS);
	client.setReadTimeout(10, TimeUnit.SECONDS);
	//添加信任https证书,用于自签名,不需要可删除
	if (url.startsWith(StringUtil.URL_PREFIXs) && socketFactory != null) {
		client.setSslSocketFactory(socketFactory);
	}

	return client;
}
 
Example 5
Project: LoRaWAN-Smart-Parking   File: HttpEngine.java   View source code 6 votes vote down vote up
/**
 * @param requestHeaders the client's supplied request headers. This class
 *     creates a private copy that it can mutate.
 * @param connection the connection used for an intermediate response
 *     immediately prior to this request/response pair, such as a same-host
 *     redirect. This engine assumes ownership of the connection and must
 *     release it when it is unneeded.
 */
public HttpEngine(OkHttpClient client, Policy policy, String method, RawHeaders requestHeaders,
    Connection connection, RetryableOutputStream requestBodyOut) throws IOException {
  this.client = client;
  this.policy = policy;
  this.method = method;
  this.connection = connection;
  this.requestBodyOut = requestBodyOut;

  try {
    uri = Platform.get().toUriLenient(policy.getURL());
  } catch (URISyntaxException e) {
    throw new IOException(e.getMessage());
  }

  this.requestHeaders = new RequestHeaders(uri, new RawHeaders(requestHeaders));
}
 
Example 6
Project: promagent   File: WildflyIT.java   View source code 6 votes vote down vote up
/**
 * Run some HTTP queries against a Docker container from image promagent/wildfly-kitchensink-promagent.
 * <p/>
 * The Docker container is started by the maven-docker-plugin when running <tt>mvn verify -Pwildfly</tt>.
 */
@Test
public void testWildfly() throws Exception {
    OkHttpClient client = new OkHttpClient();
    Request restRequest = new Request.Builder().url(System.getProperty("deployment.url") + "/rest/members").build();

    // Execute REST call
    Response restResponse = client.newCall(restRequest).execute();
    Assertions.assertEquals(restResponse.code(), 200);
    Assertions.assertTrue(restResponse.body().string().contains("John Smith"));

    Thread.sleep(100); // metric is incremented after servlet has written the response, wait a little to get the updated metric
    assertMetrics(client, "1.0");

    // Execute REST call again
    restResponse = client.newCall(restRequest).execute();
    Assertions.assertEquals(restResponse.code(), 200);
    Assertions.assertTrue(restResponse.body().string().contains("John Smith"));

    Thread.sleep(100); // metric is incremented after servlet has written the response, wait a little to get the updated metric
    assertMetrics(client, "2.0");
}
 
Example 7
Project: APIJSON-Android-RxJava   File: HttpManager.java   View source code 6 votes vote down vote up
/**
 * @param url
 * @return
 */
private OkHttpClient getHttpClient(String url) {
	Log.i(TAG, "getHttpClient  url = " + url);
	if (StringUtil.isNotEmpty(url, true) == false) {
		Log.e(TAG, "getHttpClient  StringUtil.isNotEmpty(url, true) == false >> return null;");
		return null;
	}

	OkHttpClient client = new OkHttpClient();
	client.setCookieHandler(new HttpHead());
	client.setConnectTimeout(15, TimeUnit.SECONDS);
	client.setWriteTimeout(10, TimeUnit.SECONDS);
	client.setReadTimeout(10, TimeUnit.SECONDS);

	return client;
}
 
Example 8
Project: APIJSON-Android-RxJava   File: HttpManager.java   View source code 6 votes vote down vote up
/**
 * @param url
 * @return
 */
private OkHttpClient getHttpClient(String url) {
	Log.i(TAG, "getHttpClient  url = " + url);
	if (StringUtil.isNotEmpty(url, true) == false) {
		Log.e(TAG, "getHttpClient  StringUtil.isNotEmpty(url, true) == false >> return null;");
		return null;
	}

	OkHttpClient client = new OkHttpClient();
	client.setCookieHandler(new HttpHead());
	client.setConnectTimeout(15, TimeUnit.SECONDS);
	client.setWriteTimeout(10, TimeUnit.SECONDS);
	client.setReadTimeout(10, TimeUnit.SECONDS);
	//添加信任https证书,用于自签名,不需要可删除
	if (url.startsWith(StringUtil.URL_PREFIXs) && socketFactory != null) {
		client.setSslSocketFactory(socketFactory);
	}

	return client;
}
 
Example 9
Project: weex-3d-map   File: WXWebSocketManager.java   View source code 6 votes vote down vote up
public void connect(String url) {
  try {
    mHttpClient= (OkHttpClient) Class.forName("com.squareup.okhttp.OkHttpClient").newInstance();
  } catch (Exception e) {
    isSupportWebSocket =false;
    return;
  }
  mHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
  mHttpClient.setWriteTimeout(10, TimeUnit.SECONDS);
  // Disable timeouts for read
  mHttpClient.setReadTimeout(0, TimeUnit.MINUTES);

  Request request = new Request.Builder().url(url).build();
  WebSocketCall call = WebSocketCall.create(mHttpClient, request);
  call.enqueue(this);
}
 
Example 10
Project: GitTalent   File: GithubImportService.java   View source code 6 votes vote down vote up
public GitHub initGithub() {
    String tmpDirPath = System.getProperty("java.io.tmpdir");
    File cacheDirectoryParent = new File(tmpDirPath);
    File cacheDirectory = new File(cacheDirectoryParent, "okhttpCache");
    if (!cacheDirectory.exists()) {
        cacheDirectory.mkdir();
    }
    Cache cache = new Cache(cacheDirectory, 100 * 1024 * 1024);
    try {
        return GitHubBuilder.fromCredentials()
                .withRateLimitHandler(RateLimitHandler.WAIT)
                .withAbuseLimitHandler(AbuseLimitHandler.WAIT)
                .withConnector(new OkHttpConnector(new OkUrlFactory(new OkHttpClient().setCache(cache))))
                .build();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 11
Project: Library-Token-Automation   File: LoginActivity.java   View source code 6 votes vote down vote up
Call post(Callback callback) throws IOException {
    OkHttpClient client = getUnsafeOkHttpClient();
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    client.setCookieHandler(cookieManager);
    RequestBody requestBody = new FormEncodingBuilder()
            .add("user_id", NetId)
            .add("user_password", password)
            .build();
    Request request = new Request.Builder()
            .url("https://studentmaintenance.webapps.snu.edu.in/students/public/studentslist/studentslist/loginauth")
            .post(requestBody)
            .build();
    Call call = client.newCall(request);
    call.enqueue(callback);
    return call;
}
 
Example 12
Project: Expert-Android-Programming   File: RetroInterface.java   View source code 6 votes vote down vote up
private static RestAdapter getRestAdapter() {

        RequestInterceptor requestInterceptor = new RequestInterceptor() {
            @Override
            public void intercept(RequestFacade request) {
                request.addHeader(Constant.TAG_TOKEN, Constant.APP_TOKEN);
            }
        };

        return new RestAdapter.Builder()
                .setLogLevel(LOG_LEVEL)
                .setEndpoint(RetroInterface.TARGET_URL)
                .setRequestInterceptor(requestInterceptor)
                .setClient(new OkClient(new OkHttpClient()))
                .build();
    }
 
Example 13
Project: Expert-Android-Programming   File: RetroInterface.java   View source code 6 votes vote down vote up
private static RestAdapter getImageApiAdapter() {

        RequestInterceptor requestInterceptor = new RequestInterceptor() {
            @Override
            public void intercept(RequestFacade request) {
                request.addHeader(Constant.TAG_TOKEN, Constant.APP_TOKEN);
            }
        };

        return new RestAdapter.Builder()
                .setLogLevel(LOG_LEVEL)
                .setEndpoint(RetroInterface.TARGET_URL)
                .setRequestInterceptor(requestInterceptor)
                .setClient(new OkClient(new OkHttpClient()))
                .build();
    }
 
Example 14
Project: boohee_v5.6   File: HttpEngine.java   View source code 6 votes vote down vote up
public HttpEngine(OkHttpClient client, Request request, boolean bufferRequestBody, boolean
        callerWritesRequestBody, boolean forWebSocket, StreamAllocation streamAllocation,
                  RetryableSink requestBodyOut, Response priorResponse) {
    this.client = client;
    this.userRequest = request;
    this.bufferRequestBody = bufferRequestBody;
    this.callerWritesRequestBody = callerWritesRequestBody;
    this.forWebSocket = forWebSocket;
    if (streamAllocation == null) {
        streamAllocation = new StreamAllocation(client.getConnectionPool(), createAddress
                (client, request));
    }
    this.streamAllocation = streamAllocation;
    this.requestBodyOut = requestBodyOut;
    this.priorResponse = priorResponse;
}
 
Example 15
Project: LoRaWAN-Smart-Parking   File: HttpEngine.java   View source code 6 votes vote down vote up
/**
 * @param requestHeaders the client's supplied request headers. This class
 *     creates a private copy that it can mutate.
 * @param connection the connection used for an intermediate response
 *     immediately prior to this request/response pair, such as a same-host
 *     redirect. This engine assumes ownership of the connection and must
 *     release it when it is unneeded.
 */
public HttpEngine(OkHttpClient client, Policy policy, String method, RawHeaders requestHeaders,
    Connection connection, RetryableOutputStream requestBodyOut) throws IOException {
  this.client = client;
  this.policy = policy;
  this.method = method;
  this.connection = connection;
  this.requestBodyOut = requestBodyOut;

  try {
    uri = Platform.get().toUriLenient(policy.getURL());
  } catch (URISyntaxException e) {
    throw new IOException(e.getMessage());
  }

  this.requestHeaders = new RequestHeaders(uri, new RawHeaders(requestHeaders));
}
 
Example 16
Project: GitHub   File: ApiServiceModule.java   View source code 5 votes vote down vote up
@Provides
@Singleton
OkHttpClient provideOkHttpClient() {
    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setConnectTimeout(60 * 1000, TimeUnit.MILLISECONDS);
    okHttpClient.setReadTimeout(60 * 1000, TimeUnit.MILLISECONDS);
    return okHttpClient;
}
 
Example 17
Project: GitHub   File: ApiServiceModule.java   View source code 5 votes vote down vote up
@Provides
@Singleton
RestAdapter provideRestAdapter(Application application, OkHttpClient okHttpClient) {
    RestAdapter.Builder builder = new RestAdapter.Builder();
    builder.setClient(new OkClient(okHttpClient))
            .setEndpoint(ENDPOINT);
    return builder.build();
}
 
Example 18
Project: GitHub   File: HttpManager.java   View source code 5 votes vote down vote up
/**
 * @param client
 * @param request
 * @return
 * @throws Exception
 */
private String getResponseJson(OkHttpClient client, Request request) throws Exception {
	if (client == null || request == null) {
		Log.e(TAG, "getResponseJson  client == null || request == null >> return null;");
		return null;
	}
	Response response = client.newCall(request).execute();
	return response.isSuccessful() ? response.body().string() : null;
}
 
Example 19
Project: GitHub   File: OkHttpHelper.java   View source code 5 votes vote down vote up
public OkHttpHelper() {

        mHttpClient = new OkHttpClient();
        mHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
        mHttpClient.setReadTimeout(10, TimeUnit.SECONDS);
        mHttpClient.setWriteTimeout(30, TimeUnit.SECONDS);
        mGson = new Gson();

        mHandler = new Handler(Looper.getMainLooper());

    }
 
Example 20
Project: GitHub   File: ApiConnection.java   View source code 5 votes vote down vote up
private void connectToApi() {
  OkHttpClient okHttpClient = this.createClient();
  final Request request = new Request.Builder()
      .url(this.url)
      .addHeader(CONTENT_TYPE_LABEL, CONTENT_TYPE_VALUE_JSON)
      .get()
      .build();

  try {
    this.response = okHttpClient.newCall(request).execute().body().string();
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example 21
Project: GitHub   File: ApiConnection.java   View source code 5 votes vote down vote up
private OkHttpClient createClient() {
  final OkHttpClient okHttpClient = new OkHttpClient();
  okHttpClient.setReadTimeout(10000, TimeUnit.MILLISECONDS);
  okHttpClient.setConnectTimeout(15000, TimeUnit.MILLISECONDS);

  return okHttpClient;
}
 
Example 22
Project: scmt-server   File: DeskClient.java   View source code 5 votes vote down vote up
private OkHttpClient createOkHttpClient() {
    OkHttpClient okHttpClient = new OkHttpClient();

    // if we have response cache let's use it!
    if (responseCache != null) {
        okHttpClient.setCache(responseCache);
    }

    // add auth interceptors
    switch (authType) {
        case OAUTH:
            if (oAuthConsumer == null) {
                throw new IllegalStateException("a RetrofitHttpOAuthConsumer must be created before creating OKClient");
            }
            okHttpClient.interceptors().add(new OAuthSigningInterceptor(oAuthConsumer));
            break;
        case API_TOKEN:
            okHttpClient.interceptors().add(new ApiTokenSigningInterceptor(apiToken));
            break;
        default:
            throw new IllegalStateException("AuthType " + authType + " isn't supported.");
    }

    // add all other application interceptors
    if (applicationInterceptors != null && !applicationInterceptors.isEmpty()) {
        okHttpClient.interceptors().addAll(applicationInterceptors);
    }

    // add all other network interceptors
    if (networkInterceptors != null && !networkInterceptors.isEmpty()) {
        okHttpClient.networkInterceptors().addAll(networkInterceptors);
    }

    return okHttpClient;
}
 
Example 23
Project: publicProject   File: GlobalVariable.java   View source code 5 votes vote down vote up
/**
 * @return RequestQueue
 */
public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(mContext, new OkHttpStack(new OkHttpClient()));
    }
    mRequestQueue.getCache().clear();
    return mRequestQueue;
}
 
Example 24
Project: afp-api-client   File: ApiClient.java   View source code 5 votes vote down vote up
public ApiClient() {
    httpClient = new OkHttpClient();

    verifyingSsl = true;

    json = new JSON(this);

    /*
     * Use RFC3339 format for date and datetime.
     * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14
     */
    this.dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    // Always use UTC as the default time zone when dealing with date (without time).
    this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    initDatetimeFormat();

    // Be lenient on datetime formats when parsing datetime from string.
    // See <code>parseDatetime</code>.
    this.lenientDatetimeFormat = true;

    // Set default User-Agent.
    setUserAgent("INA; OTMedia; afp-api-client v0.3.0");

    // Setup authentications (key: authentication name, value: authentication).
    authentications = new HashMap<String, Authentication>();
    authentications.put("oauth2", new OAuth());
    // Prevent the authentications from being modified.
    authentications = Collections.unmodifiableMap(authentications);
}
 
Example 25
Project: RoadLab-Pro   File: RestClient.java   View source code 5 votes vote down vote up
public OkHttpClient getUnsafeOkHttpClient() {
    try {
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setSslSocketFactory(getSslSocketFactory());
        okHttpClient.setHostnameVerifier(new NullHostNameVerifier());
        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 26
Project: code-examples-android-expert   File: OkhttpTestWithRxJava.java   View source code 5 votes vote down vote up
@Before
public void setup() {
    client = new OkHttpClient();

    request = new Request.Builder()
            .url("http://www.vogella.com/index.html")
            .build();
}
 
Example 27
Project: ComponentDemo   File: RemoteService.java   View source code 5 votes vote down vote up
public static synchronized RemoteService getInstance() {
    if (service == null) {
        service = new RemoteService();
        mOkHttpClient = new OkHttpClient();
    }
    return service;
}
 
Example 28
Project: APIJSON-Android-RxJava   File: HttpManager.java   View source code 5 votes vote down vote up
/**
 * @param client
 * @param request
 * @return
 * @throws Exception
 */
private String getResponseJson(OkHttpClient client, Request request) throws Exception {
	if (client == null || request == null) {
		Log.e(TAG, "getResponseJson  client == null || request == null >> return null;");
		return null;
	}
	Response response = client.newCall(request).execute();
	return response.isSuccessful() ? response.body().string() : null;
}
 
Example 29
Project: APIJSON-Android-RxJava   File: HttpManager.java   View source code 5 votes vote down vote up
/**
 * @param client
 * @param request
 * @return
 * @throws Exception
 */
private String getResponseJson(OkHttpClient client, Request request) throws Exception {
	if (client == null || request == null) {
		Log.e(TAG, "getResponseJson  client == null || request == null >> return null;");
		return null;
	}
	Response response = client.newCall(request).execute();
	return response.isSuccessful() ? response.body().string() : null;
}
 
Example 30
Project: Hello-Music-droid   File: RestServiceFactory.java   View source code 5 votes vote down vote up
public static <T> T createStatic(final Context context, String baseUrl, Class<T> clazz) {
    final OkHttpClient okHttpClient = new OkHttpClient();

    okHttpClient.setCache(new Cache(context.getApplicationContext().getCacheDir(),
            CACHE_SIZE));
    okHttpClient.setConnectTimeout(40, TimeUnit.SECONDS);

    RequestInterceptor interceptor = new RequestInterceptor() {
        PreferencesUtility prefs = PreferencesUtility.getInstance(context);

        @Override
        public void intercept(RequestFacade request) {
            //7-days cache
            request.addHeader("Cache-Control", String.format("max-age=%d,%smax-stale=%d", Integer.valueOf(60 * 60 * 24 * 7), prefs.loadArtistImages() ? "" : "only-if-cached,", Integer.valueOf(31536000)));
            request.addHeader("Connection", "keep-alive");
        }
    };

    RestAdapter.Builder builder = new RestAdapter.Builder()
            .setEndpoint(baseUrl)
            .setRequestInterceptor(interceptor)
            .setClient(new OkClient(okHttpClient));

    return builder
            .build()
            .create(clazz);

}
 
Example 31
Project: Build-it-Bigger   File: RetrofitTest.java   View source code 5 votes vote down vote up
@Test
public void testGetJokes() throws IOException {

    //Building the RestAdapter again because UrlFetchClient needs appengine module
    // and doesn't work during testing. Also, OkClient is not supported by GCE
    RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint(ServiceGenerator.API_ENDPOINT_URL)
            .setClient(new OkClient(new OkHttpClient()))
            .build();
    ApiInterface apiInterface = restAdapter.create(ApiInterface.class);
    assertEquals("Incorrect response : ", 5, apiInterface.getRandomJokesSync(5).getJokeList().size());
}
 
Example 32
Project: weex-3d-map   File: WXOkHttpDispatcher.java   View source code 5 votes vote down vote up
private static OkHttpClient defaultOkHttpClient() {
  OkHttpClient client = new OkHttpClient();
  client.networkInterceptors().add(new OkHttpInterceptor());
  client.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
  client.setReadTimeout(DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
  client.setWriteTimeout(DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
  return client;
}
 
Example 33
Project: coner-core-client-java   File: ApiClient.java   View source code 5 votes vote down vote up
public ApiClient() {
    httpClient = new OkHttpClient();

    verifyingSsl = true;

    json = new JSON(this);

    /*
     * Use RFC3339 format for date and datetime.
     * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14
     */
    this.dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    // Always use UTC as the default time zone when dealing with date (without time).
    this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    initDatetimeFormat();

    // Be lenient on datetime formats when parsing datetime from string.
    // See <code>parseDatetime</code>.
    this.lenientDatetimeFormat = true;

    // Set default User-Agent.
    setUserAgent("Swagger-Codegen/0.1.20/java");

    // Setup authentications (key: authentication name, value: authentication).
    authentications = new HashMap<String, Authentication>();
    // Prevent the authentications from being modified.
    authentications = Collections.unmodifiableMap(authentications);
}
 
Example 34
Project: xlight_android_native   File: ApiFactory.java   View source code 5 votes vote down vote up
private static OkHttpClient buildClientWithTimeout(int timeoutInSeconds) {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(timeoutInSeconds, TimeUnit.SECONDS);
    client.setReadTimeout(timeoutInSeconds, TimeUnit.SECONDS);
    client.setWriteTimeout(timeoutInSeconds, TimeUnit.SECONDS);
    return client;
}
 
Example 35
Project: xlight_android_native   File: ApiFactory.java   View source code 5 votes vote down vote up
private RestAdapter.Builder buildCommonRestAdapterBuilder(Gson gson, OkHttpClient client) {
    return new RestAdapter.Builder()
            .setClient(new OkClient(client))
            .setConverter(new GsonConverter(gson))
            .setEndpoint(getApiUri().toString())
            .setLogLevel(LogLevel.valueOf(ctx.getString(R.string.http_log_level)));
}
 
Example 36
Project: AndroidNetwork   File: RemoteService.java   View source code 5 votes vote down vote up
public static synchronized RemoteService getInstance() {
    if (service == null) {
        service = new RemoteService();
        mOkHttpClient = new OkHttpClient();

        //设置超时时间
        //参见:OkHttp3超时设置和超时异常捕获
        //http://blog.csdn.net/do168/article/details/51848895
        mOkHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
        mOkHttpClient.setWriteTimeout(10, TimeUnit.SECONDS);
        mOkHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
    }
    return service;
}
 
Example 37
Project: AndroidNetwork   File: RemoteService.java   View source code 5 votes vote down vote up
public static synchronized RemoteService getInstance() {
    if (service == null) {
        service = new RemoteService();
        mOkHttpClient = new OkHttpClient();
    }
    return service;
}
 
Example 38
Project: AndroidNetwork   File: RemoteService.java   View source code 5 votes vote down vote up
public static synchronized RemoteService getInstance() {
    if (service == null) {
        service = new RemoteService();
        mOkHttpClient = new OkHttpClient();
    }
    return service;
}
 
Example 39
Project: AndroidNetwork   File: RemoteService.java   View source code 5 votes vote down vote up
public static synchronized RemoteService getInstance() {
    if (service == null) {
        service = new RemoteService();
        mOkHttpClient = new OkHttpClient();
    }
    return service;
}
 
Example 40
Project: AndroidNetwork   File: RemoteService.java   View source code 5 votes vote down vote up
public static synchronized RemoteService getInstance() {
    if (service == null) {
        service = new RemoteService();
        mOkHttpClient = new OkHttpClient();

        //设置超时时间
        //参见:OkHttp3超时设置和超时异常捕获
        //http://blog.csdn.net/do168/article/details/51848895
        mOkHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
        mOkHttpClient.setWriteTimeout(10, TimeUnit.SECONDS);
        mOkHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
    }
    return service;
}