Java 类com.squareup.okhttp.OkHttpClient 实例源码
项目:owa-notifier
文件:RestfullAcessProxy.java
/**
* 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);
}
项目:GitHub
文件:OkhttpDemoActivity.java
@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();
}
项目:GitHub
文件:HttpManager.java
/**
* @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;
}
项目:GitHub
文件:HttpManager.java
/**
* @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;
}
项目:LoRaWAN-Smart-Parking
文件:HttpEngine.java
/**
* @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));
}
项目:promagent
文件:WildflyIT.java
/**
* 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");
}
项目:APIJSON-Android-RxJava
文件:HttpManager.java
/**
* @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;
}
项目:APIJSON-Android-RxJava
文件:HttpManager.java
/**
* @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;
}
项目:weex-3d-map
文件:WXWebSocketManager.java
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);
}
项目:GitTalent
文件:GithubImportService.java
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);
}
}
项目:Library-Token-Automation
文件:LoginActivity.java
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;
}
项目:Expert-Android-Programming
文件:RetroInterface.java
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();
}
项目:Expert-Android-Programming
文件:RetroInterface.java
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();
}
项目:boohee_v5.6
文件:HttpEngine.java
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;
}
项目:LoRaWAN-Smart-Parking
文件:HttpEngine.java
/**
* @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));
}
项目:GitHub
文件:ApiServiceModule.java
@Provides
@Singleton
OkHttpClient provideOkHttpClient() {
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setConnectTimeout(60 * 1000, TimeUnit.MILLISECONDS);
okHttpClient.setReadTimeout(60 * 1000, TimeUnit.MILLISECONDS);
return okHttpClient;
}
项目:GitHub
文件:ApiServiceModule.java
@Provides
@Singleton
RestAdapter provideRestAdapter(Application application, OkHttpClient okHttpClient) {
RestAdapter.Builder builder = new RestAdapter.Builder();
builder.setClient(new OkClient(okHttpClient))
.setEndpoint(ENDPOINT);
return builder.build();
}
项目:GitHub
文件:HttpManager.java
/**
* @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;
}
项目:GitHub
文件:OkHttpHelper.java
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());
}
项目:GitHub
文件:ApiConnection.java
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();
}
}
项目:GitHub
文件:ApiConnection.java
private OkHttpClient createClient() {
final OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setReadTimeout(10000, TimeUnit.MILLISECONDS);
okHttpClient.setConnectTimeout(15000, TimeUnit.MILLISECONDS);
return okHttpClient;
}
项目:scmt-server
文件:DeskClient.java
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;
}
项目:publicProject
文件:GlobalVariable.java
/**
* @return RequestQueue
*/
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(mContext, new OkHttpStack(new OkHttpClient()));
}
mRequestQueue.getCache().clear();
return mRequestQueue;
}
项目:afp-api-client
文件:ApiClient.java
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);
}
项目:RoadLab-Pro
文件:RestClient.java
public OkHttpClient getUnsafeOkHttpClient() {
try {
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setSslSocketFactory(getSslSocketFactory());
okHttpClient.setHostnameVerifier(new NullHostNameVerifier());
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
项目:code-examples-android-expert
文件:OkhttpTestWithRxJava.java
@Before
public void setup() {
client = new OkHttpClient();
request = new Request.Builder()
.url("http://www.vogella.com/index.html")
.build();
}
项目:ComponentDemo
文件:RemoteService.java
public static synchronized RemoteService getInstance() {
if (service == null) {
service = new RemoteService();
mOkHttpClient = new OkHttpClient();
}
return service;
}
项目:APIJSON-Android-RxJava
文件:HttpManager.java
/**
* @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;
}
项目:APIJSON-Android-RxJava
文件:HttpManager.java
/**
* @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;
}
项目:Hello-Music-droid
文件:RestServiceFactory.java
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);
}
项目:Build-it-Bigger
文件:RetrofitTest.java
@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());
}
项目:weex-3d-map
文件:WXOkHttpDispatcher.java
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;
}
项目:coner-core-client-java
文件:ApiClient.java
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);
}
项目:xlight_android_native
文件:ApiFactory.java
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;
}
项目:xlight_android_native
文件:ApiFactory.java
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)));
}
项目:AndroidNetwork
文件:RemoteService.java
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;
}
项目:AndroidNetwork
文件:RemoteService.java
public static synchronized RemoteService getInstance() {
if (service == null) {
service = new RemoteService();
mOkHttpClient = new OkHttpClient();
}
return service;
}
项目:AndroidNetwork
文件:RemoteService.java
public static synchronized RemoteService getInstance() {
if (service == null) {
service = new RemoteService();
mOkHttpClient = new OkHttpClient();
}
return service;
}
项目:AndroidNetwork
文件:RemoteService.java
public static synchronized RemoteService getInstance() {
if (service == null) {
service = new RemoteService();
mOkHttpClient = new OkHttpClient();
}
return service;
}
项目:AndroidNetwork
文件:RemoteService.java
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;
}