Java Code Examples for com.squareup.okhttp.Response#code()
The following examples show how to use
com.squareup.okhttp.Response#code() .
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 File: QiitaBaseApi.java From Qiitanium with MIT License | 6 votes |
protected <T> ResponseDto<T> execute(Request.Builder request, Type type) { try { final Response response = execute(request); if (!response.isSuccessful()) { throw new WebAccessException(response.code(), fetchErrorMessage(response)); } final ResponseDto<T> dto = new ResponseDto<T>(); dto.body = objectify(response, type); dto.page = fetchPagenationHeader(response); return dto; } catch (IOException ioe) { throw new DataAccessException(ioe); } }
Example 2
Source File: GithubClient.java From MOE with Apache License 2.0 | 6 votes |
String getResponseJson(PullRequestUrl id) { Request request = new Request.Builder() .url(id.apiAddress()) .addHeader("User-Agent", "OkHttpClient/1.0 (Make Open Easy repository sync software)") .build(); try { Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { switch (response.code()) { case 404: throw new InvalidGithubUrl("No such pull request found: %s", id); case 403: throw new InvalidGithubUrl("Github rate-limit reached - please wait 60 mins: %s", id); default: throw new IOException("Unexpected code " + response); } } return response.body().string(); } catch (IOException ioe) { throw new RuntimeException(ioe); } }
Example 3
Source File: MizLib.java From Mizuu with Apache License 2.0 | 6 votes |
public static JSONObject getJSONObject(Context context, String url) { final OkHttpClient client = MizuuApplication.getOkHttpClient(); Request request = new Request.Builder() .url(url) .get() .build(); try { Response response = client.newCall(request).execute(); if (response.code() >= 429) { // HTTP error 429 and above means that we've exceeded the query limit // for TMDb. Sleep for 5 seconds and try again. Thread.sleep(5000); response = client.newCall(request).execute(); } return new JSONObject(response.body().string()); } catch (Exception e) { // IOException and JSONException return new JSONObject(); } }
Example 4
Source File: MyTaskService.java From android-gcmnetworkmanager with Apache License 2.0 | 6 votes |
private int fetchUrl(OkHttpClient client, String url) { Request request = new Request.Builder() .url(url) .build(); try { Response response = client.newCall(request).execute(); Log.d(TAG, "fetchUrl:response:" + response.body().string()); if (response.code() != 200) { return GcmNetworkManager.RESULT_FAILURE; } } catch (IOException e) { Log.e(TAG, "fetchUrl:error" + e.toString()); return GcmNetworkManager.RESULT_FAILURE; } return GcmNetworkManager.RESULT_SUCCESS; }
Example 5
Source File: ApiClient.java From ariADDna with Apache License 2.0 | 6 votes |
/** * Execute HTTP call and deserialize the HTTP response body into the given return type. * * @param returnType The return type used to deserialize HTTP response body * @param <T> The return type corresponding to (same with) returnType * @param call Call * @return ApiResponse object containing response status, headers and * data, which is a Java object deserialized from response body and would be null * when returnType is null. * @throws ApiException If fail to execute the call */ public <T> ApiResponse<T> execute(Call call, Type returnType) throws ApiException { try { Response response = call.execute(); LOGGER.info("Method {execute} was called, with params isExecuted: {}, returnType: {}", call.isExecuted(), returnType == null ? null : returnType.getTypeName()); T data = handleResponse(response, returnType); return new ApiResponse<T>(response.code(), response.headers().toMultimap(), data); } catch (IOException e) { LOGGER.error("Method {execute} was called, with params :{},{}", call.isExecuted(), returnType == null ? null : returnType.getTypeName()); LOGGER.error("Method {execute} throw exception: " + e); throw new ApiException(e); } }
Example 6
Source File: OkHttpClient2xPluginIT.java From glowroot with Apache License 2.0 | 6 votes |
@Override public void transactionMarker() throws Exception { MediaType mediaType = MediaType.parse("text/plain; charset=utf-8"); OkHttpClient client = new OkHttpClient(); RequestBody body = RequestBody.create(mediaType, "hello"); Request request = new Request.Builder() .url("http://localhost:" + getPort() + "/hello2") .post(body) .build(); Response response = client.newCall(request).execute(); if (response.code() != 200) { throw new IllegalStateException( "Unexpected response status code: " + response.code()); } response.body().close(); }
Example 7
Source File: HarborClient.java From harbor-java-client with Apache License 2.0 | 6 votes |
/** * This endpoint returns all projects created by Harbor, and can be filtered * by project name.</br> * <b>URL</b>: /projects</br> * <b>Method</b>: GET * * @param projectName * (Project name for filtering results) * @param isPublic * (Public sign for filtering projects) * @return * @throws IOException * @throws HarborClientException */ public List<Project> getProjects(String projectName, String isPublic) throws IOException, HarborClientException { List<NameValuePair> qparams = new ArrayList<>(); qparams.add(new BasicNameValuePair("project_name", projectName)); qparams.add(new BasicNameValuePair("is_public", isPublic)); qparams.removeIf(o -> Objects.isNull(o.getValue())); String url = getBaseUrl() + "projects?" + URLEncodedUtils.format(qparams, "UTF-8"); Request request = new Request.Builder().url(url).get().build(); Response response = okhttpClient.newCall(request).execute(); logger.debug(String.format(REQUEST_RESPONSE_INFO, request, response)); if (response.code() != 200) { throw new HarborClientException(String.valueOf(response.code()), response.message()); } return mapper.readValue(response.body().string(), new TypeReference<List<Project>>() { }); }
Example 8
Source File: HarborClient.java From harbor-java-client with Apache License 2.0 | 5 votes |
/** * Let user search repositories accompanying with relevant project ID and * repo name.</br> * <b>URL</b>: /repositories</br> * <b>Method</b>: GET * * @param projectId * [required] (Relevant project ID) * @param q * (Repo name for filtering results) * @return respositories * @throws IOException * @throws HarborClientException */ public List<String> getRepositories(String projectId, String q) throws IOException, HarborClientException { String url = getBaseUrl() + "repositories?project_id=" + projectId; if (q != null) { url = url + "&q=" + q; } Request request = new Request.Builder().url(url).get().build(); Response response = okhttpClient.newCall(request).execute(); logger.debug(String.format(REQUEST_RESPONSE_INFO, request, response)); if (response.code() != 200) { throw new HarborClientException(String.valueOf(response.code()), response.message()); } return mapper.readValue(response.body().string(), new TypeReference<List<String>>() { }); }
Example 9
Source File: WXOkHttpDispatcher.java From weex with Apache License 2.0 | 5 votes |
@Override public void handleMessage(Message msg) { int what = msg.what; switch (what) { case SUBMIT: { WXHttpTask task = (WXHttpTask) msg.obj; Request.Builder builder = new Request.Builder().header("User-Agent", "WeAppPlusPlayground/1.0").url(task.url); WXHttpResponse httpResponse = new WXHttpResponse(); try { Response response = mOkHttpClient.newCall(builder.build()).execute(); httpResponse.code = response.code(); httpResponse.data = response.body().bytes(); task.response = httpResponse; mUiHandler.sendMessage(mUiHandler.obtainMessage(1, task)); } catch (Throwable e) { e.printStackTrace(); httpResponse.code = 1000; mUiHandler.sendMessage(mUiHandler.obtainMessage(1, task)); } } break; default: break; } }
Example 10
Source File: HostConnection.java From Kore with Apache License 2.0 | 5 votes |
/** * Reads the response from the server * @param response Response from OkHttp * @return Response body string * @throws ApiException {@link ApiException} if response can't be read/processed */ private String handleOkHttpResponse(Response response) throws ApiException { try { // LogUtils.LOGD(TAG, "Reading HTTP response."); int responseCode = response.code(); switch (responseCode) { case 200: // All ok, read response String res = response.body().string(); response.body().close(); LogUtils.LOGD(TAG, "OkHTTP response: " + res); return res; case 401: LogUtils.LOGD(TAG, "OkHTTP response read error. Got a 401: " + response); throw new ApiException(ApiException.HTTP_RESPONSE_CODE_UNAUTHORIZED, "Server returned response code: " + response); case 404: LogUtils.LOGD(TAG, "OkHTTP response read error. Got a 404: " + response); throw new ApiException(ApiException.HTTP_RESPONSE_CODE_NOT_FOUND, "Server returned response code: " + response); default: LogUtils.LOGD(TAG, "OkHTTP response read error. Got: " + response); throw new ApiException(ApiException.HTTP_RESPONSE_CODE_UNKNOWN, "Server returned response code: " + response); } } catch (IOException e) { LogUtils.LOGW(TAG, "Failed to read OkHTTP response.", e); throw new ApiException(ApiException.IO_EXCEPTION_WHILE_READING_RESPONSE, e); } }
Example 11
Source File: OkHttpClient2xPluginIT.java From glowroot with Apache License 2.0 | 5 votes |
@Override public void transactionMarker() throws Exception { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("http://localhost:" + getPort() + "/hello1/") .build(); Response response = client.newCall(request).execute(); if (response.code() != 200) { throw new IllegalStateException( "Unexpected response status code: " + response.code()); } response.body().close(); }
Example 12
Source File: HttpURLConnectionImpl.java From apiman with Apache License 2.0 | 5 votes |
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 13
Source File: HarborClient.java From harbor-java-client with Apache License 2.0 | 5 votes |
/** * For user to create a new project.</br> * <b>URL</b>: /projects</br> * <b>Method</b>: POST * * @param project * [required] (New created project) * @return * @throws IOException */ public HarborResponse createProject(Project project) throws IOException { HarborResponse result = new HarborResponse(); String res; String url = baseUrl + "projects"; RequestBody requestBody = RequestBody.create(JSON, mapper.writeValueAsString(project)); Request request = new Request.Builder().url(url).post(requestBody).build(); Response response = okhttpClient.newCall(request).execute(); logger.debug(String.format(REQUEST_RESPONSE_INFO, request, response)); switch (response.code()) { case 201: res = "Project created successfully."; break; case 400: res = "Unsatisfied with constraints of the project creation."; break; case 401: res = "User need to log in first."; break; case 409: res = "Project name already exists."; break; case 500: res = "Unexpected internal errors."; break; default: res = "Unknown."; break; } result.setCode(Integer.toString(response.code())); result.setMessage(res); return result; }
Example 14
Source File: HarborClient.java From harbor-java-client with Apache License 2.0 | 5 votes |
/** * Create a user if the user does not already exist.</br> * <b>URL</b>: /users</br> * <b>Method</b>: POST * * @param user * [required] (New created user) * @return * @throws IOException */ public HarborResponse createUser(ProjectMember user) throws IOException { HarborResponse result = new HarborResponse(); String res; String url = baseUrl + "users"; RequestBody requestBody = RequestBody.create(JSON, mapper.writeValueAsString(user)); Request request = new Request.Builder().url(url).post(requestBody).build(); Response response = okhttpClient.newCall(request).execute(); logger.debug(String.format(REQUEST_RESPONSE_INFO, request, response)); switch (response.code()) { case 201: res = "User created successfully."; break; case 400: res = "Unsatisfied with constraints of the user creation."; break; case 403: res = "User registration can only be used by admin role user when self-registration is off."; break; case 409: res = "username has already been used."; break; case 500: res = "Unexpected internal errors."; break; default: res = "Unknown."; break; } result.setCode(Integer.toString(response.code())); result.setMessage(res); return result; }
Example 15
Source File: WXOkHttpDispatcher.java From incubator-weex-playground with Apache License 2.0 | 5 votes |
@Override public void handleMessage(Message msg) { int what = msg.what; switch (what) { case SUBMIT: { WXHttpTask task = (WXHttpTask) msg.obj; Request.Builder builder = new Request.Builder().header("User-Agent", "WeAppPlusPlayground/1.0").url(task.url); WXHttpResponse httpResponse = new WXHttpResponse(); try { Response response = mOkHttpClient.newCall(builder.build()).execute(); httpResponse.code = response.code(); httpResponse.data = response.body().bytes(); task.response = httpResponse; mUiHandler.sendMessage(mUiHandler.obtainMessage(1, task)); } catch (Throwable e) { e.printStackTrace(); httpResponse.code = 1000; mUiHandler.sendMessage(mUiHandler.obtainMessage(1, task)); } } break; default: break; } }
Example 16
Source File: Downloader.java From external-resources with Apache License 2.0 | 5 votes |
public Resources load(@Cache.Policy int policy) throws ExternalResourceException { buildUrl(); Logger.i(ExternalResources.TAG, "Load configuration from url: " + url.build()); final CacheControl cacheControl; switch (policy) { case Cache.POLICY_NONE: cacheControl = new CacheControl.Builder().noCache().noStore().build(); break; case Cache.POLICY_OFFLINE: cacheControl = CacheControl.FORCE_CACHE; break; case Cache.POLICY_ALL: default: cacheControl = new CacheControl.Builder().build(); break; } Logger.v(ExternalResources.TAG, "CachePolicy: " + policy); Request request = new Request.Builder().url(url.build()).cacheControl(cacheControl).build(); try { Response response = client.newCall(request).execute(); int responseCode = response.code(); Logger.d(ExternalResources.TAG, "Response code: " + responseCode); if (responseCode >= 300) { response.body().close(); throw new ResponseException(responseCode + " " + response.message(), policy, responseCode); } return converter.fromReader(response.body().charStream()); } catch (IOException e) { throw new ExternalResourceException(e); } }
Example 17
Source File: OkHttpStack.java From OkVolley with Apache License 2.0 | 4 votes |
/** * perform the request * * @param request request * @param additionalHeaders headers * @return http response * @throws java.io.IOException * @throws com.android.volley.AuthFailureError */ @Override public Response performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders()); map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } com.squareup.okhttp.Request.Builder builder = new com.squareup.okhttp.Request.Builder(); builder.url(url); for (String headerName : map.keySet()) { builder.header(headerName, map.get(headerName)); // connection.addRequestProperty(headerName, map.get(headerName)); if (VolleyLog.DEBUG) { // print header message VolleyLog.d("RequestHeader: %1$s:%2$s", headerName, map.get(headerName)); } } setConnectionParametersForRequest(builder, request); // Initialize HttpResponse with data from the okhttp. Response okHttpResponse = mClient.newCall(builder.build()).execute(); int responseCode = okHttpResponse.code(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } return okHttpResponse; }
Example 18
Source File: HarborClient.java From harbor-java-client with Apache License 2.0 | 3 votes |
/** * For user to get role members accompany with relevant project and * user.</br> * <b>URL</b>: /projects/{project_id}/members/{user_id}</br> * <b>Method</b>: GET * * @param projectId * [required] (Relevant project ID) * @param userId * [required] (Relevant user ID) * @return role members * @throws IOException * @throws HarborClientException */ public Member getRole(int projectId, int userId) throws IOException, HarborClientException { String url = getBaseUrl() + "projects/" + projectId + "/members/" + userId; Request request = new Request.Builder().url(url).get().build(); Response response = okhttpClient.newCall(request).execute(); logger.debug(String.format(REQUEST_RESPONSE_INFO, request, response)); if (response.code() != 200) { throw new HarborClientException(String.valueOf(response.code()), response.message()); } return mapper.readValue(response.body().string(), Member.class); }
Example 19
Source File: HarborClient.java From harbor-java-client with Apache License 2.0 | 3 votes |
/** * Statistic all of the projects number and repositories number relevant to * the logined user, also the public projects number and repositories * number. </br> * <b>URL</b>: /statistics</br> * <b>Method</b>: GET * * @return The projects number and repositories number relevant to the user. * @throws IOException * @throws HarborClientException */ public ProjectAndRepoNum getStatistics() throws IOException, HarborClientException { String url = getBaseUrl() + "statistics"; Request request = new Request.Builder().url(url).get().build(); Response response = okhttpClient.newCall(request).execute(); logger.debug(String.format(REQUEST_RESPONSE_INFO, request, response)); if (response.code() != 200) { throw new HarborClientException(String.valueOf(response.code()), response.message()); } return mapper.readValue(response.body().string(), ProjectAndRepoNum.class); }
Example 20
Source File: HarborClient.java From harbor-java-client with Apache License 2.0 | 3 votes |
/** * The Search endpoint returns information about the projects and * repositories offered at public status or related to the current logged in * user. </br> * <b>URL</b>: /search</br> * <b><b>Method</b>: GET</b> * * @param q * [required] (Search parameter for project and repository name) * @return The response includes the project and repository list in a proper * display order. * @throws IOException * @throws HarborClientException */ public Search search(String q) throws IOException, HarborClientException { String url = getBaseUrl() + "search?q=" + q; Request request = new Request.Builder().url(url).get().build(); Response response = okhttpClient.newCall(request).execute(); logger.debug(String.format(REQUEST_RESPONSE_INFO, request, response)); if (response.code() != 200) { throw new HarborClientException(String.valueOf(response.code()), response.message()); } return mapper.readValue(response.body().string(), Search.class); }