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

项目:GitHub    文件:OkHttpNetworkFetcher.java   
@Override
public void fetch(final OkHttpNetworkFetchState fetchState, final Callback callback) {
  fetchState.submitTime = SystemClock.uptimeMillis();
  final Uri uri = fetchState.getUri();

  try {
    Request request = new Request.Builder()
      .cacheControl(new CacheControl.Builder().noStore().build())
      .url(uri.toString())
      .get()
      .build();
    fetchWithRequest(fetchState, callback, request);
  } catch (Exception e) {
    // handle error while creating the request
    callback.onFailure(e);
  }
}
项目:rkt-launcher    文件:ClientTest.java   
@Test
public void shouldSendGetRequest() throws ExecutionException, InterruptedException {
  final Request request = new com.squareup.okhttp.Request.Builder()
      .url(URI)
      .method("GET", null)
      .build();
  when(okHttpClient.newCall(argThat(new RequestMatcher(request)))).thenReturn(call);
  doAnswer(invocation -> {
    final Callback callback = invocation.getArgument(0);
    callback.onResponse(new Response.Builder()
                            .request(request)
                            .protocol(Protocol.HTTP_1_1)
                            .code(Status.OK.code())
                            .message("OK")
                            .body(ResponseBody.create(CONTENT_TYPE, "{}"))
                            .header("foo", "bar")
                            .build());
    return Void.TYPE;
  }).when(call).enqueue(isA(Callback.class));
  final com.spotify.apollo.Response<ByteString> response =
      client.send(com.spotify.apollo.Request.forUri(URI, "GET")).toCompletableFuture().get();
  verify(okHttpClient, never()).setReadTimeout(anyLong(), any());

  assertEquals(Optional.of(ByteString.of("{}".getBytes())), response.payload());
  assertEquals(Optional.of("bar"), response.header("foo"));
}
项目:rkt-launcher    文件:ClientTest.java   
@Test
public void shouldSendGetRequestAndReceiveException() {
  final Request request = new com.squareup.okhttp.Request.Builder()
      .url(URI)
      .method("GET", null)
      .build();
  when(okHttpClient.newCall(argThat(new RequestMatcher(request)))).thenReturn(call);
  doAnswer(invocation -> {
    final Callback callback = invocation.getArgument(0);
    callback.onFailure(request, new IOException());
    return Void.TYPE;
  }).when(call).enqueue(isA(Callback.class));
  final CompletionStage<com.spotify.apollo.Response<ByteString>> response =
      client.send(com.spotify.apollo.Request.forUri(URI, "GET").withTtl(Duration.ofMillis(100)));
  verify(okHttpClient).setReadTimeout(100, TimeUnit.MILLISECONDS);
  assertTrue(response.toCompletableFuture().isCompletedExceptionally());
}
项目:find-client-android    文件:FindWiFiImpl.java   
@Override
protected Void doInBackground(Void... params) {

    try {
        Request.Builder requestBuilder = new Request.Builder()
                .url(serverAddr + urlPart);
        switch (method) {
            case PUT:
                requestBuilder.put(RequestBody.create(MEDIA_TYPE_JSON, json));
                break;
            case POST:
                requestBuilder.post(RequestBody.create(MEDIA_TYPE_JSON, json));
                break;
            case DELETE:
                requestBuilder.delete(RequestBody.create(MEDIA_TYPE_JSON, json));
                break;
            default: break;
        }
        Request request = requestBuilder.build();
        httpClient.newCall(request).enqueue(new HttpCallback(callback));
    } catch (Exception e) {
        Log.e(TAG, "IOException", e);
    }
    return null;
}
项目: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");
}
项目:AIMSICDL    文件:DeviceFragment.java   
private Request createOpenCellIdApiCall() {
    StringBuilder sb = new StringBuilder();
    sb.append("http://www.opencellid.org/cell/get?key=").append(CellTracker.OCID_API_KEY);

    if (mAimsicdService.getCell().getMCC() != Integer.MAX_VALUE) {
        sb.append("&mcc=").append(mAimsicdService.getCell().getMCC());
    }
    if (mAimsicdService.getCell().getMNC() != Integer.MAX_VALUE) {
        sb.append("&mnc=").append(mAimsicdService.getCell().getMNC());
    }
    if (mAimsicdService.getCell().getLAC() != Integer.MAX_VALUE) {
        sb.append("&lac=").append(mAimsicdService.getCell().getLAC());
    }
    if (mAimsicdService.getCell().getCID() != Integer.MAX_VALUE) {
        sb.append("&cellid=").append(mAimsicdService.getCell().getCID());
    }
    sb.append("&format=json");
    return new Request.Builder()
            .url(sb.toString())
            .get()
            .build();
}
项目: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);
}
项目:weex-3d-map    文件:WXWebSocketManager.java   
@Override
public void onOpen(WebSocket webSocket, Request arg1, Response arg2)
    throws IOException {
  mWebSocket = webSocket;
  setEnvironment(WXEnvironment.getConfig());
  WXSDKManager.getInstance().postOnUiThread(new Runnable() {
    @Override
    public void run() {
      Toast.makeText(WXEnvironment.sApplication, "Has switched to DEBUG mode, you can see the DEBUG information on the browser!", Toast.LENGTH_SHORT).show();
    }
  },0);
  for (JSDebuggerCallback callback : mCallbacks.values()) {
    callback.onSuccess(arg2);
  }
  WXLogUtils.e("into--[onOpen]");
}
项目:pre-dem-android    文件:OkHttp2Probe.java   
@Around("call(* com.squareup.okhttp.OkHttpClient+.newCall(..))")
public Object onOkHttpNew(ProceedingJoinPoint joinPoint) throws Throwable {
    if (!Configuration.httpMonitorEnable || joinPoint.getArgs().length != 1) {
        return joinPoint.proceed();
    }
    Object[] args = joinPoint.getArgs();
    Request request = (Request) args[0];

    //url
    URL url = request.url();
    if (GlobalConfig.isExcludeHost(url.getHost())) {
        return joinPoint.proceed();
    }
    RespBean bean = new RespBean();
    bean.setUrl(url.toString());
    bean.setStartTimestamp(System.currentTimeMillis());
    startTimeStamp.add(bean);
    return joinPoint.proceed();
}
项目: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;
}
项目:robird-reborn    文件:TweetMarkerUtils.java   
public static long get(String collection, String user) {
    try {
        collection = "lists." + Long.parseLong(collection);
    } catch (NumberFormatException ignored) {

    }

    Request request = new Request.Builder()
            .url(TWEETMARKER_API_URL + "?api_key=" + API_KEY + "&username=" + user + "&collection" + collection)
            .get()
            .build();

    try {
        final Response response = createHttpClientWithoutSSL().newCall(request).execute();
        JSONObject json = new JSONObject(response.body().string());
        return json.getJSONObject(collection).getLong("id");
    } catch (IOException | JSONException | NoSuchAlgorithmException | KeyManagementException e) {
        Timber.i(e, "");
    }

    return -1;
}
项目:boohee_v5.6    文件:Http2xStream.java   
public void writeRequestHeaders(Request request) throws IOException {
    if (this.stream == null) {
        List<Header> requestHeaders;
        this.httpEngine.writingRequestHeaders();
        boolean permitsRequestBody = this.httpEngine.permitsRequestBody(request);
        if (this.framedConnection.getProtocol() == Protocol.HTTP_2) {
            requestHeaders = http2HeadersList(request);
        } else {
            requestHeaders = spdy3HeadersList(request);
        }
        this.stream = this.framedConnection.newStream(requestHeaders, permitsRequestBody, true);
        this.stream.readTimeout().timeout((long) this.httpEngine.client.getReadTimeout(),
                TimeUnit.MILLISECONDS);
        this.stream.writeTimeout().timeout((long) this.httpEngine.client.getWriteTimeout(),
                TimeUnit.MILLISECONDS);
    }
}
项目: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;
}
项目:boohee_v5.6    文件:HttpEngine.java   
private Request networkRequest(Request request) throws IOException {
    Request.Builder result = request.newBuilder();
    if (request.header("Host") == null) {
        result.header("Host", Util.hostHeader(request.httpUrl()));
    }
    if (request.header("Connection") == null) {
        result.header("Connection", "Keep-Alive");
    }
    if (request.header(AsyncHttpClient.HEADER_ACCEPT_ENCODING) == null) {
        this.transparentGzip = true;
        result.header(AsyncHttpClient.HEADER_ACCEPT_ENCODING, AsyncHttpClient.ENCODING_GZIP);
    }
    CookieHandler cookieHandler = this.client.getCookieHandler();
    if (cookieHandler != null) {
        OkHeaders.addCookies(result, cookieHandler.get(request.uri(), OkHeaders.toMultimap
                (result.build().headers(), null)));
    }
    if (request.header(Network.USER_AGENT) == null) {
        result.header(Network.USER_AGENT, Version.userAgent());
    }
    return result.build();
}
项目:Logistics-guard    文件:OkHttpClientManager.java   
/**
 * 同步的Get请求
 *
 * @param url
 * @return Response
 */
private Response _getAsyn(String url) throws IOException {
    final Request request = new Request.Builder()
            .url(url)
            .build();
    Call call = mOkHttpClient.newCall(request);
    Response execute = call.execute();
    return execute;
}
项目:Logistics-guard    文件:OkHttpClientManager.java   
/**
 * 异步的get请求
 *
 * @param url
 * @param callback
 */
private void _getAsyn(String url, final ResultCallback callback) {
    final Request request = new Request.Builder()
            .url(url)
            .build();
    deliveryResult(callback, request);
}
项目:Library-Token-Automation    文件:MainActivity.java   
Call post(String mode, String username, String password, Callback callback) throws IOException {
    OkHttpClient client = new OkHttpClient();
    RequestBody formBody = new FormEncodingBuilder()
            .add("mode", mode)
            .add("username", username + "@snu.in")
            .add("password", password)
            .build();
    Request request = new Request.Builder()
            .url("http://192.168.50.1/24online/servlet/E24onlineHTTPClient")
            .post(formBody)
            .build();
    Call call = client.newCall(request);
    call.enqueue(callback);
    return call;
}
项目:Logistics-guard    文件:OkHttpClientManager.java   
private Request buildMultipartFormRequest(String url, File[] files,
                                          String[] fileKeys, Param[] params) {
    params = validateParam(params);

    MultipartBuilder builder = new MultipartBuilder()
            .type(MultipartBuilder.FORM);

    for (Param param : params) {
        builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + param.key + "\""),
                RequestBody.create(null, param.value));
    }
    if (files != null) {
        RequestBody fileBody = null;
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            String fileName = file.getName();
            fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file);
            //TODO 根据文件名设置contentType
            builder.addPart(Headers.of("Content-Disposition",
                    "form-data; name=\"" + fileKeys[i] + "\"; filename=\"" + fileName + "\""),
                    fileBody);
        }
    }

    RequestBody requestBody = builder.build();
    return new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
}
项目:Logistics-guard    文件:OkHttpClientManager.java   
private void sendFailedStringCallback(final Request request, final Exception e, final ResultCallback callback) {
    mDelivery.post(new Runnable() {
        @Override
        public void run() {
            if (callback != null)
                callback.onError(request, e);
        }
    });
}
项目:Logistics-guard    文件:OkHttpClientManager.java   
private Request buildPostRequest(String url, Param[] params) {
    if (params == null) {
        params = new Param[0];
    }
    FormEncodingBuilder builder = new FormEncodingBuilder();
    for (Param param : params) {
        builder.add(param.key, param.value);
    }
    RequestBody requestBody = builder.build();
    return new Request.Builder()
            .url(url)
            .post(requestBody)
            .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;
}
项目:boohee_v5.6    文件:RequestLine.java   
static String get(Request request, Type proxyType) {
    StringBuilder result = new StringBuilder();
    result.append(request.method());
    result.append(' ');
    if (includeAuthorityInRequestLine(request, proxyType)) {
        result.append(request.httpUrl());
    } else {
        result.append(requestPath(request.httpUrl()));
    }
    result.append(" HTTP/1.1");
    return result.toString();
}
项目: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    文件:Pager.java   
@Override
public void onFailure(Request request, Exception e) {

    dismissDialog();
    Toast.makeText(builder.mContext, "请求出错:" + e.getMessage(), Toast.LENGTH_LONG).show();

    if (STATE_REFREH == state) {
        builder.mRefreshLayout.finishRefresh();
    } else if (STATE_MORE == state) {

        builder.mRefreshLayout.finishRefreshLoadMore();
    }
}
项目:GitHub    文件:OkHttpHelper.java   
private void callbackFailure(final BaseCallback callback, final Request request, final IOException e) {

        mHandler.post(new Runnable() {
            @Override
            public void run() {
                callback.onFailure(request, e);
            }
        });
    }
项目:ImageLoaderSupportGif    文件:OkHttpImageDownloader.java   
@Override
protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
    Request request = new Request.Builder().url(imageUri).build();
    ResponseBody responseBody = client.newCall(request).execute().body();
    InputStream inputStream = responseBody.byteStream();
    int contentLength = (int) responseBody.contentLength();
    return new ContentLengthInputStream(inputStream, contentLength);
}
项目:GitHub    文件:OkHttpImageDownloader.java   
@Override
protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
    Request request = new Request.Builder().url(imageUri).build();
    ResponseBody responseBody = client.newCall(request).execute().body();
    InputStream inputStream = responseBody.byteStream();
    int contentLength = (int) responseBody.contentLength();
    return new ContentLengthInputStream(inputStream, contentLength);
}
项目: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();
  }
}
项目:kubernetes-client    文件:WebSockets.java   
public static Listener stream(String path, String method, List<Pair> queryParams, ApiClient client, io.kubernetes.client.util.WebSockets.SocketListener listener) throws ApiException, IOException {

    HashMap<String, String> headers = new HashMap<String, String>();
    String allProtocols = String.format("%s,%s,%s,%s", V4_STREAM_PROTOCOL, V3_STREAM_PROTOCOL, V2_STREAM_PROTOCOL, V1_STREAM_PROTOCOL);
    headers.put(STREAM_PROTOCOL_HEADER, allProtocols);
    headers.put(HttpHeaders.CONNECTION, HttpHeaders.UPGRADE);
    headers.put(HttpHeaders.UPGRADE, SPDY_3_1);

    String[] localVarAuthNames = new String[] { "BearerToken" };
    Request request = client.buildRequest(path, method, queryParams, new ArrayList<Pair>(), null, headers, new HashMap<String, Object>(), localVarAuthNames, null);
    return streamRequest(request, client, listener);
}
项目:rkt-launcher    文件:ClientTest.java   
@Test
public void shouldSendPostRequest() throws ExecutionException, InterruptedException {
  final Request request = new com.squareup.okhttp.Request.Builder()
      .url(URI)
      .method("POST", RequestBody.create(CONTENT_TYPE, "{}"))
      .build();
  when(okHttpClient.newCall(argThat(new RequestMatcher(request)))).thenReturn(call);
  doAnswer(invocation -> {
    final Callback callback = invocation.getArgument(0);
    callback.onResponse(new Response.Builder()
                            .request(request)
                            .protocol(Protocol.HTTP_1_1)
                            .code(Status.OK.code())
                            .message("OK")
                            .body(ResponseBody.create(CONTENT_TYPE, "{}"))
                            .header("foo", "bar")
                            .build());
    return Void.TYPE;
  }).when(call).enqueue(isA(Callback.class));
  final com.spotify.apollo.Response<ByteString> response =
      client.send(com.spotify.apollo.Request
                      .forUri(URI, "POST")
                      .withPayload(ByteString.of("{}".getBytes())))
          .toCompletableFuture().get();
  verify(okHttpClient, never()).setReadTimeout(anyLong(), any());

  assertEquals(Optional.of(ByteString.of("{}".getBytes())), response.payload());
  assertEquals(Optional.of("bar"), response.header("foo"));
}
项目:Go-RxJava    文件:Fragment_Okhttp.java   
public String execute2String(Request request) {

            String result = null;
            try {
                Response response = okHttpClient.newCall(request).execute();
                if (response != null && response.isSuccessful()) {
                    result = response.body().string();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }
项目:Go-RxJava    文件:Fragment_Okhttp.java   
/**
 * 创建一个工作在IO线程的被观察者(被订阅者)对象
 *
 * @param url
 */
public <T> Observable<T> createObservable(final String url, final Class<T> clazz) {
    return Observable.create(new Observable.OnSubscribe<T>() {
        @Override
        public void call(Subscriber<? super T> subscriber) {
            Request.Builder request = new Request.Builder();

            Request.Builder builder = request.url(url);
            String json = execute2String(builder.build());
            setData(subscriber, json, clazz);
        }
    }).subscribeOn(Schedulers.io());
}
项目:find-client-android    文件:HttpCallback.java   
@Override
public void onFailure(final Request request, final IOException e) {
    handler.post(new Runnable() {
        @Override
        public void run() {
            delegate.onFailure(request, e);
        }
    });
}
项目:xwallet    文件:TwitterAuthApi.java   
/**
 *
 * @param params
 * @return
 */
@Override
protected String doInBackground(Void... params) {

    OkHttpClient client = new OkHttpClient();

    String cred = Credentials.basic(_key, _secret);

    FormEncodingBuilder formBody = new FormEncodingBuilder();
    formBody.add("grant_type", "client_credentials");

    Request request = new Request.Builder()
            .url(TWITTER_AUTH_URL)
            .post(formBody.build())
            .addHeader("Authorization", cred)
            .addHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8")
            .addHeader("Accept-Encoding", "gzip")
            .build();

    try {
        Response response = client.newCall(request).execute();

        if (isZipped(response)) {
            return unzip(response.body());
        } else {
            return response.body().string();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
项目: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();
}
项目: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;
}
项目:xwallet    文件:CexChartAPI.java   
/**
 *
 * @param params
 * @return
 */
@Override
protected String doInBackground(Void... params) {
    OkHttpClient client = new OkHttpClient();

    HttpUrl httpUrl = HttpUrl.parse(COIN_DESK_API_URL);
    //System.out.println("Requesting : " + httpUrl.toString());

    FormEncodingBuilder formBody = new FormEncodingBuilder();
    formBody.add("lastHours", "24");
    formBody.add("maxRespArrSize", "24");

    Request request = new Request.Builder()
            .url(httpUrl)
            .post(formBody.build())
            .build();

    String content = null;
    try {
        Response response = client.newCall(request).execute();
        ResponseBody body = response.body();

        if (isZipped(response)) {
            content = unzip(body);
        } else {
            content = body.string();
        }

        body.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return content;
}
项目: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;
}
项目:AIMSICDL    文件:DeviceFragment.java   
@Override
public void onRefresh() {
    if (CellTracker.OCID_API_KEY != null && !CellTracker.OCID_API_KEY.equals("NA")) {
        Request request = createOpenCellIdApiCall();
        okHttpClient.newCall(request).enqueue(getOpenCellIdResponseCallback());
    } else {
        Handler refresh = new Handler(Looper.getMainLooper());
        refresh.post(new Runnable() {
            public void run() {
                Helpers.sendMsg(getActivity(), getString(R.string.no_opencellid_key_detected));
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }
}
项目:weex-3d-map    文件:HotRefreshManager.java   
public boolean connect(String url) {
  OkHttpClient httpClient = new OkHttpClient();
  Request request = new Request.Builder().url(url).addHeader("sec-websocket-protocol", "echo-protocol").build();
  WebSocketCall.create(httpClient, request).enqueue(new WXWebSocketListener(url));

  return true;
}