當前位置: 首頁>>代碼示例>>Java>>正文


Java OkHttpClient類代碼示例

本文整理匯總了Java中com.squareup.okhttp.OkHttpClient的典型用法代碼示例。如果您正苦於以下問題:Java OkHttpClient類的具體用法?Java OkHttpClient怎麽用?Java OkHttpClient使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


OkHttpClient類屬於com.squareup.okhttp包,在下文中一共展示了OkHttpClient類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getRealTokenService

import com.squareup.okhttp.OkHttpClient; //導入依賴的package包/類
/**
 * 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);
}
 
開發者ID:OwaNotifier,項目名稱:owa-notifier,代碼行數:28,代碼來源:RestfullAcessProxy.java

示例2: onCreate

import com.squareup.okhttp.OkHttpClient; //導入依賴的package包/類
@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();
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:17,代碼來源:OkhttpDemoActivity.java

示例3: getHttpClient

import com.squareup.okhttp.OkHttpClient; //導入依賴的package包/類
/**
 * @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;
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:24,代碼來源:HttpManager.java

示例4: HttpEngine

import com.squareup.okhttp.OkHttpClient; //導入依賴的package包/類
/**
 * @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));
}
 
開發者ID:aabognah,項目名稱:LoRaWAN-Smart-Parking,代碼行數:25,代碼來源:HttpEngine.java

示例5: testWildfly

import com.squareup.okhttp.OkHttpClient; //導入依賴的package包/類
/**
 * 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");
}
 
開發者ID:fstab,項目名稱:promagent,代碼行數:27,代碼來源:WildflyIT.java

示例6: getHttpClient

import com.squareup.okhttp.OkHttpClient; //導入依賴的package包/類
/**
 * @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;
}
 
開發者ID:TommyLemon,項目名稱:APIJSON-Android-RxJava,代碼行數:20,代碼來源:HttpManager.java

示例7: connect

import com.squareup.okhttp.OkHttpClient; //導入依賴的package包/類
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);
}
 
開發者ID:amap-demo,項目名稱:weex-3d-map,代碼行數:17,代碼來源:WXWebSocketManager.java

示例8: initGithub

import com.squareup.okhttp.OkHttpClient; //導入依賴的package包/類
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);
    }
}
 
開發者ID:couchbaselabs,項目名稱:GitTalent,代碼行數:19,代碼來源:GithubImportService.java

示例9: post

import com.squareup.okhttp.OkHttpClient; //導入依賴的package包/類
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;
}
 
開發者ID:anuragsai97,項目名稱:Library-Token-Automation,代碼行數:18,代碼來源:LoginActivity.java

示例10: getRestAdapter

import com.squareup.okhttp.OkHttpClient; //導入依賴的package包/類
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();
    }
 
開發者ID:PacktPublishing,項目名稱:Expert-Android-Programming,代碼行數:17,代碼來源:RetroInterface.java

示例11: getImageApiAdapter

import com.squareup.okhttp.OkHttpClient; //導入依賴的package包/類
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();
    }
 
開發者ID:PacktPublishing,項目名稱:Expert-Android-Programming,代碼行數:17,代碼來源:RetroInterface.java

示例12: HttpEngine

import com.squareup.okhttp.OkHttpClient; //導入依賴的package包/類
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;
}
 
開發者ID:JackChan1999,項目名稱:boohee_v5.6,代碼行數:17,代碼來源:HttpEngine.java

示例13: provideOkHttpClient

import com.squareup.okhttp.OkHttpClient; //導入依賴的package包/類
@Provides
@Singleton
OkHttpClient provideOkHttpClient() {
    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setConnectTimeout(60 * 1000, TimeUnit.MILLISECONDS);
    okHttpClient.setReadTimeout(60 * 1000, TimeUnit.MILLISECONDS);
    return okHttpClient;
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:9,代碼來源:ApiServiceModule.java

示例14: provideRestAdapter

import com.squareup.okhttp.OkHttpClient; //導入依賴的package包/類
@Provides
@Singleton
RestAdapter provideRestAdapter(Application application, OkHttpClient okHttpClient) {
    RestAdapter.Builder builder = new RestAdapter.Builder();
    builder.setClient(new OkClient(okHttpClient))
            .setEndpoint(ENDPOINT);
    return builder.build();
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:9,代碼來源:ApiServiceModule.java

示例15: getResponseJson

import com.squareup.okhttp.OkHttpClient; //導入依賴的package包/類
/**
 * @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;
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:15,代碼來源:HttpManager.java


注:本文中的com.squareup.okhttp.OkHttpClient類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。