Java Code Examples for com.squareup.okhttp.Response

The following examples show how to use com.squareup.okhttp.Response. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Pas   Source File: DOkHttp.java    License: Apache License 2.0 6 votes vote down vote up
/**
     * 获取cookie
     * @param response
     * @param url
     */
    private Map getCookie(Response response, String url) {
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        //获取cookie 然后打印  绑定
        try {
            List<String> values = response.headers().values("Set-Cookie");
            map = getInstance().mOkHttpClient.getCookieHandler().get(URI.create(url), response.headers().toMultimap());

//            for (String key : map.keySet()) {
//                if ("Cookie".equals(key)) {
//                    sessionId = map.get(key).get(0);
//                }
//            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return  map;
    }
 
Example 2
Source Project: materialup   Source File: Api.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Response intercept(Chain chain) throws IOException {
    Response originalResponse = chain.proceed(chain.request());

    String host = chain.request().url().getHost();
    if (isMatchHost(host)) {
        if (!originalResponse.headers("Set-Cookie").isEmpty()) {
            HashSet<String> cookies = new HashSet<>();
            for (String header : originalResponse.headers("Set-Cookie")) {
                cookies.add(header);
            }
            App.getPref().edit()
                    .putStringSet(PREF_COOKIES, cookies)
                    .apply();
        }
    }

    return originalResponse;
}
 
Example 3
Source Project: openzaly   Source File: ZalyHttpClient.java    License: Apache License 2.0 6 votes vote down vote up
public byte[] postBytes(String url, byte[] bytes) throws IOException {
	ResponseBody body = null;
	try {
		RequestBody postBody = RequestBody.create(JSON, bytes);
		Request request = new Request.Builder().url(url).post(postBody).build();
		Response response = httpClient.newCall(request).execute();
		if (response.isSuccessful()) {
			body = response.body();
			byte[] res = body.bytes();
			return res;
		} else {
			logger.error("http post error.{}", response.message());
		}
	} finally {
		if (body != null) {
			body.close();
		}
	}
	return null;
}
 
Example 4
Source Project: tencentcloud-sdk-java   Source File: AbstractClient.java    License: Apache License 2.0 6 votes vote down vote up
private Response doRequest(String endpoint, AbstractModel request, String action)
    throws TencentCloudSDKException {
  HashMap<String, String> param = new HashMap<String, String>();
  request.toMap(param, "");
  String strParam = this.formatRequestData(action, param);
  HttpConnection conn =
      new HttpConnection(
          this.profile.getHttpProfile().getConnTimeout(),
          this.profile.getHttpProfile().getReadTimeout(),
          this.profile.getHttpProfile().getWriteTimeout());
  conn.addInterceptors(log);
  this.trySetProxy(conn);
  String reqMethod = this.profile.getHttpProfile().getReqMethod();
  String url = this.profile.getHttpProfile().getProtocol() + endpoint + this.path;
  if (reqMethod.equals(HttpProfile.REQ_GET)) {
    return conn.getRequest(url + "?" + strParam);
  } else if (reqMethod.equals(HttpProfile.REQ_POST)) {
    return conn.postRequest(url, strParam);
  } else {
    throw new TencentCloudSDKException("Method only support (GET, POST)");
  }
}
 
Example 5
/**
 * This test defines the expected request format to be made to SwaggerHub to create an Integration plugin
 * The values defined as part of the request matcher are what is expected to be set due to the users configuration.
 * @throws JsonProcessingException
 */
@Test
public void verifySaveIntegrationPluginOfType_postsExpectedRequestBodyWithBasePath() throws JsonProcessingException {
    //Given
    swaggerHubClient = buildSwaggerHubClient("basePath");
    SaveSCMPluginConfigRequest.Builder requestBuilder = requestBuilder();
    SaveSCMPluginConfigRequest saveSCMPluginConfigRequest = requestBuilder.build();
    String requestUrl = String.format("/basePath/plugins/configurations/%s/%s/%s/%s?oas=%s", API_OWNER, API_NAME, API_VERSION, SCM_INTEGRATION_PROVIDER_GITHUB, OAS3);
    stubFor(put(requestUrl).willReturn(created()));
    RequestPatternBuilder putRequestPattern = putRequestPattern("/basePath/plugins/configurations/%s/%s/%s/%s");

    //When
    Optional<Response> response = swaggerHubClient.saveIntegrationPluginOfType(saveSCMPluginConfigRequest);

    //Then
    verify(1, putRequestPattern);
    response.ifPresent( x -> assertEquals(201, response.get().code()));
    if(!response.isPresent()){
        fail();
    }
}
 
Example 6
Source Project: RouteDrawer   Source File: RouteRest.java    License: Apache License 2.0 6 votes vote down vote up
private String getJSONDirection(LatLng start, LatLng end, TravelMode mode) throws IOException {
    String url = "http://maps.googleapis.com/maps/api/directions/json?"
            + "origin="
            + start.latitude + ","
            + start.longitude
            + "&destination="
            + end.latitude + ","
            + end.longitude
            + "&sensor=false&units=metric&mode="
            + mode.name().toLowerCase();

    Request request = new Request.Builder()
            .url(url)
            .build();

    Response response = client.newCall(request).execute();
    return response.body().string();
}
 
Example 7
Source Project: openzaly   Source File: ZalyHttpClient.java    License: Apache License 2.0 6 votes vote down vote up
public byte[] get(String url) throws Exception {
	ResponseBody body = null;
	try {
		Request request = new Request.Builder().url(url).build();
		Response response = httpClient.newCall(request).execute();
		if (response.isSuccessful()) {
			body = response.body();
			byte[] res = body.bytes();
			return res;
		} else {
			logger.error("http get url={} error.{}", url, response.message());
		}
	} finally {
		if (body != null) {
			body.close();
		}
	}
	return null;
}
 
Example 8
Source Project: openzaly   Source File: ZalyHttpClient.java    License: Apache License 2.0 6 votes vote down vote up
public byte[] postString(String url, String json) throws IOException {
	ResponseBody body = null;
	try {
		RequestBody postBody = RequestBody.create(JSON, json);
		Request request = new Request.Builder().url(url).post(postBody).build();
		Response response = httpClient.newCall(request).execute();
		if (response.isSuccessful()) {
			body = response.body();
			byte[] res = body.bytes();
			return res;
		} else {
			logger.error("http post error.{}", response.message());
		}
	} finally {
		if (body != null) {
			body.close();
		}
	}
	return null;
}
 
Example 9
Source Project: swaggerhub-gradle-plugin   Source File: SwaggerHubClient.java    License: Apache License 2.0 6 votes vote down vote up
public String getDefinition(SwaggerHubRequest swaggerHubRequest) throws GradleException {
    HttpUrl httpUrl = getDownloadUrl(swaggerHubRequest);
    MediaType mediaType = MediaType.parse("application/" + swaggerHubRequest.getFormat());

    Request requestBuilder = buildGetRequest(httpUrl, mediaType);

    final String jsonResponse;
    try {
        final Response response = client.newCall(requestBuilder).execute();
        if (!response.isSuccessful()) {
            throw new GradleException(String.format("Failed to download API definition: %s", response.body().string()));
        } else {
            jsonResponse = response.body().string();
        }
    } catch (IOException e) {
        throw new GradleException("Failed to download API definition", e);
    }
    return jsonResponse;
}
 
Example 10
Source Project: yahnac   Source File: HNewsApi.java    License: Apache License 2.0 6 votes vote down vote up
private void attemptLogin() {
    try {
        ConnectionProvider connectionProvider = Inject.connectionProvider();
        Connection.Response response = connectionProvider
                .loginConnection(username, password)
                .execute();

        String cookie = response.cookie("user");
        String cfduid = response.cookie("_cfduid");

        if (!TextUtils.isEmpty(cookie)) {
            subscriber.onNext(new Login(username, cookie, Login.Status.SUCCESSFUL));
        } else {
            subscriber.onNext(new Login(username, null, Login.Status.WRONG_CREDENTIALS));
        }

    } catch (IOException e) {
        subscriber.onError(e);
    }
}
 
Example 11
Source Project: utexas-utilities   Source File: AuthCookie.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Executes a login request with the AuthCookie's OkHttpClient. This should only be called
 * when persistent login is activated.
 * @param request Request to execute
 * @return true if the cookie was set successfully, false if the cookie was not set
 * @throws IOException
 */
protected boolean performLogin(Request request) throws IOException {
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) {
        throw new IOException("Bad response code: " + response + " during login.");
    }
    response.body().close();
    CookieManager cm = (CookieManager) CookieHandler.getDefault();
    List<HttpCookie> cookies = cm.getCookieStore().getCookies();
    for (HttpCookie cookie : cookies) {
        String cookieVal = cookie.getValue();
        if (cookie.getName().equals(authCookieKey)) {
            setAuthCookieVal(cookieVal);
            return true;
        }
    }
    return false;
}
 
Example 12
Source Project: Auth0.Android   Source File: BaseRequestTest.java    License: MIT License 6 votes vote down vote up
@Before
public void setUp() {
    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) {

        }

        @Override
        protected Request doBuildRequest() throws RequestBodyBuildException {
            return null;
        }
    };
}
 
Example 13
Source Project: apiman   Source File: HawkularMetricsClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Adds multiple data points to a counter.
 * @param tenantId
 * @param counterId
 * @param dataPoints
 */
public void addCounterDataPoints(String tenantId, String counterId, List<DataPointLongBean> dataPoints) {
    try {
        URL endpoint = serverUrl.toURI().resolve("counters/" + counterId + "/raw").toURL(); //$NON-NLS-1$ //$NON-NLS-2$
        Request request = new Request.Builder()
                .url(endpoint)
                .post(toBody(dataPoints))
                .header("Hawkular-Tenant", tenantId) //$NON-NLS-1$
                .build();
        Response response = httpClient.newCall(request).execute();
        if (response.code() >= 400) {
            throw hawkularMetricsError(response);
        }
    } catch (URISyntaxException | IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 14
Source Project: JianDan_OkHttp   Source File: PictureParser.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
public ArrayList<Picture> parse(Response response) {

    code = wrapperCode(response.code());
    if (!response.isSuccessful())
        return null;

    try {
        String jsonStr = response.body().string();
        jsonStr = new JSONObject(jsonStr).getJSONArray("comments").toString();
        return (ArrayList<Picture>) JSONParser.toObject(jsonStr,
                new TypeToken<ArrayList<Picture>>() {
                }.getType());
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 15
Source Project: mini-hacks   Source File: Login.java    License: MIT License 6 votes vote down vote up
public void login(View view) {
    String json = "{\"name\": \"" + nameInput.getText() + "\", \"password\":\"" + passwordInput.getText() + "\"}";
    networkHelper.post("http://10.0.3.2:8000/smarthome/_session", json, new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {

        }

        @Override
        public void onResponse(Response response) throws IOException {
            String responseStr = response.body().string();
            final String messageText = "Status code : " + response.code() +
                    "\n" +
                    "Response body : " + responseStr;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), messageText, Toast.LENGTH_LONG).show();
                }
            });
        }
    });
}
 
Example 16
Source Project: Pas   Source File: ProgressHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 包装OkHttpClient,用于下载文件的回调
 * @param client 待包装的OkHttpClient
 * @param progressListener 进度回调接口
 * @return 包装后的OkHttpClient,使用clone方法返回
 */
public static OkHttpClient addProgressResponseListener(OkHttpClient client, final ProgressResponseListener progressListener){
    //克隆
    OkHttpClient clone = client.clone();
    //增加拦截器
    clone.networkInterceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            //拦截
            Response originalResponse = chain.proceed(chain.request());
            //包装响应体并返回
            return originalResponse.newBuilder()
                    .body(new ProgressResponseBody(originalResponse.body(), progressListener))
                    .build();
        }
    });
    return clone;
}
 
Example 17
Source Project: materialup   Source File: Api.java    License: Apache License 2.0 6 votes vote down vote up
public static String getErrorMessage(retrofit.Response response) {
    String text = responseToString(response);
    try {
        JSONObject object = new JSONObject(text);
        if (object.has("errors")) {
            JSONArray errors = object.getJSONArray("errors");
            if (errors.length() > 0) {
                JSONObject error = errors.getJSONObject(0);
                if (error.has("message")) {
                    return error.getString("message");
                }
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    if (response.code() > 500) {
        return "check your network!";
    }
    return null;
}
 
Example 18
Source Project: fontster   Source File: FontDownloader.java    License: Apache License 2.0 6 votes vote down vote up
static Observable<File> downloadFile(final String url, final String path) {
  return Observable.create(subscriber -> {
    final Request request = new Request.Builder().url(url).build();
    try {
      if (!subscriber.isUnsubscribed()) {
        final File file = new File(path);
        if (!file.exists()) {
          // noinspection ResultOfMethodCallIgnored
          file.getParentFile().mkdirs();
          Timber.i("downloadFile: Downloading " + file.getName());
          final Response response = sClient.newCall(request).execute();
          final BufferedSink sink = Okio.buffer(Okio.sink(file));
          sink.writeAll(response.body().source());
          sink.close();
        } else Timber.i("downloadFile: Retrieved from cache " + file.getName());

        subscriber.onNext(file);
        subscriber.onCompleted();
      }
    } catch (IOException e) {
      subscriber.onError(new DownloadException(e));
    }
  });
}
 
Example 19
Source Project: apiman   Source File: HawkularMetricsClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Adds one or more data points for multiple counters all at once!
 * @param tenantId
 * @param data
 */
public void addMultipleCounterDataPoints(String tenantId, List<MetricLongBean> data) {
    try {
        URL endpoint = serverUrl.toURI().resolve("counters/raw").toURL(); //$NON-NLS-1$
        Request request = new Request.Builder()
                .url(endpoint)
                .post(toBody(data))
                .header("Hawkular-Tenant", tenantId) //$NON-NLS-1$
                .build();
        Response response = httpClient.newCall(request).execute();
        if (response.code() >= 400) {
            throw hawkularMetricsError(response);
        }
    } catch (URISyntaxException | IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 20
Source Project: spring-async   Source File: AggregatorService.java    License: MIT License 6 votes vote down vote up
public void execute(final Task task) {
    log.info("Started task with {} urls", task.getUrls().size());
    task.start();
    for(int i = 0; i < task.getUrls().size(); i++) {
        final int index = i;
        final long time = System.currentTimeMillis();
        String url = task.getUrls().get(i);
        Request req = new Request.Builder().get().url(url).build();

        client.newCall(req).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                task.fail(index, time, request, e);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                task.success(index, time, response);
            }
        });
    }
}
 
Example 21
Source Project: Social   Source File: OkHttpService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void likeNews(String newsId, final NetCallback netCallback) {
    OkhttpUtil.getIns().likeNews(newsId, new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            netCallback.onFail(e.getMessage());
        }

        @Override
        public void onResponse(Response response) throws IOException {
            handleStringResponse(response.body().string(), netCallback);
        }
    });
}
 
Example 22
Source Project: Social   Source File: OkHttpService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void login(String username, String password, final NetCallback netCallback) {
    OkhttpUtil.getIns().login(username, password, new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            netCallback.onFail(e.getMessage());
        }

        @Override
        public void onResponse(Response response) throws IOException {
            handleStringResponse(response.body().string(),netCallback);
        }
    });
}
 
Example 23
Source Project: apiman   Source File: HttpURLConnectionImpl.java    License: Apache License 2.0 5 votes vote down vote up
private static String responseSourceHeader(Response response) {
  if (response.networkResponse() == null) {
    if (response.cacheResponse() == null) {
      return "NONE";
    }
    return "CACHE " + response.code();
  }
  if (response.cacheResponse() == null) {
    return "NETWORK " + response.code();
  }
  return "CONDITIONAL_CACHE " + response.networkResponse().code();
}
 
Example 24
Source Project: wind-im   Source File: HttpTestPost.java    License: Apache License 2.0 5 votes vote down vote up
static String post(String url, String json) throws IOException {
	RequestBody body = RequestBody.create(JSON, json);
	Request request = new Request.Builder().url(url).post(body).build();
	Response response = client.newCall(request).execute();
	System.out.println("response = " + response.isSuccessful());
	if (response.isSuccessful()) {
		return response.body().string();
	} else {
		throw new IOException("Unexpected code " + response);
	}
}
 
Example 25
Source Project: apiman   Source File: HttpURLConnectionImpl.java    License: Apache License 2.0 5 votes vote down vote up
private Headers getHeaders() throws IOException {
  if (responseHeaders == null) {
    Response response = getResponse().getResponse();
    Headers headers = response.headers();

    responseHeaders = headers.newBuilder()
        .add(Platform.get().getPrefix() + "-Response-Source", responseSourceHeader(response))
        .build();
  }
  return responseHeaders;
}
 
Example 26
Source Project: pre-dem-android   Source File: OkHttp2Probe.java    License: MIT License 5 votes vote down vote up
@Around("call(* com.squareup.okhttp.Response.Builder+.build(..))")
public Object onOkHttpRespBuild(ProceedingJoinPoint joinPoint) throws Throwable {
    if (!Configuration.httpMonitorEnable) {
        return joinPoint.proceed();
    }
    Object result = joinPoint.proceed();
    if (result instanceof Response) {
        Response resp = (Response) result;
        RespBodyToRespMap.put(resp.body(), resp);
    }
    return result;
}
 
Example 27
Source Project: openzaly   Source File: HttpClient.java    License: Apache License 2.0 5 votes vote down vote up
static String postJson(String url, String json) throws IOException {
	MediaType JSON = MediaType.parse("application/json; charset=utf-8");
	RequestBody postBody = RequestBody.create(JSON, json);
	Request request = new Request.Builder().url(url).post(postBody).build();
	Response response = client.newCall(request).execute();
	System.out.println("post postJson response =" + response.isSuccessful());
	if (response.isSuccessful()) {
		return response.body().toString();
	} else {
		System.out.println("http post failed");
		throw new IOException("post json Unexpected code " + response);
	}
}
 
Example 28
Source Project: openzaly   Source File: HttpTestPost.java    License: Apache License 2.0 5 votes vote down vote up
static String post(String url, String json) throws IOException {
	RequestBody body = RequestBody.create(JSON, json);
	Request request = new Request.Builder().url(url).post(body).build();
	Response response = client.newCall(request).execute();
	System.out.println("response = " + response.isSuccessful());
	if (response.isSuccessful()) {
		return response.body().string();
	} else {
		throw new IOException("Unexpected code " + response);
	}
}
 
Example 29
Source Project: weex   Source File: WXWebsocketBridge.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onSuccess(Response response) {
    if(response.isSuccessful()){
        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);
    }
}
 
Example 30
@Override
protected void onDataRefresh() {

    Utils.getRawHtmlFromUrl(articleBean.getUrl(), new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            Log.d(TAG, "onFailure: " + e.getMessage());
        }

        @Override
        public void onResponse(final Response response) throws IOException {
            final String rawData = response.body().string();
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(new Runnable() {
                @Override
                public void run() {
                    ScienceContentParser myParse = new ScienceContentParser(rawData);
                    String data = myParse.getEndStr();
                    scrollView.setVisibility(View.VISIBLE);
                    scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
                        @Override
                        public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                            topImage.setTranslationY(Math.max(-scrollY / 2, -DisplayUtil.dip2px(getBaseContext(), 170)));
                        }
                    });
                    contentView.loadDataWithBaseURL("file:///android_asset/", "<link rel=\"stylesheet\" type=\"text/css\" href=\"guokr.css\" />" + data, "text/html", "utf-8", null);
                }
            });
        }
    });
    if(HttpUtil.isWIFI == true || Settings.getInstance().getBoolean(Settings.NO_PIC_MODE, false) == false) {
        setMainContentBg(articleBean.getImage_info().getUrl());
    }

    hideLoading();
}