@Override public Drawable getDrawable(final String source) { try { Drawable repositoryImage = requestRepositoryImage(source); if (repositoryImage != null) return repositoryImage; } catch (Exception e) { // Ignore and attempt request over regular HTTP request } try { String logMessage = "Loading image: " + source; Log.d(getClass().getSimpleName(), logMessage); Bugsnag.leaveBreadcrumb(logMessage); Request request = new Request.Builder().get().url(source).build(); com.squareup.okhttp.Response response = okHttpClient.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected response code: " + response.code()); Bitmap bitmap = BitmapFactory.decodeStream(response.body().byteStream()); if (bitmap == null) return loading.getDrawable(source); BitmapDrawable drawable = new BitmapDrawable(context.getResources(), bitmap); drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight()); return drawable; } catch (IOException e) { Log.e(getClass().getSimpleName(), "Error loading image", e); Bugsnag.notify(e); return loading.getDrawable(source); } }
public Request authenticateProxy(Proxy paramProxy, Response paramResponse) { List localList = paramResponse.challenges(); paramResponse = paramResponse.request(); URL localURL = paramResponse.url(); int i = 0; int j = localList.size(); while (i < j) { Object localObject = (Challenge) localList.get(i); if ("Basic".equalsIgnoreCase(((Challenge) localObject).getScheme())) { InetSocketAddress localInetSocketAddress = (InetSocketAddress) paramProxy.address(); localObject = java.net.Authenticator.requestPasswordAuthentication( localInetSocketAddress.getHostName(), getConnectToInetAddress(paramProxy, localURL), localInetSocketAddress.getPort(), localURL.getProtocol(), ((Challenge) localObject).getRealm(), ((Challenge) localObject).getScheme(), localURL, Authenticator.RequestorType.PROXY); if (localObject != null) { paramProxy = Credentials.basic( ((PasswordAuthentication) localObject).getUserName(), new String(((PasswordAuthentication) localObject).getPassword())); return paramResponse.newBuilder().header("Proxy-Authorization", paramProxy).build(); } } i += 1; } return null; }
public boolean saveFile(Response response) { // Message msg = new Message(); InputStream is = null; FileOutputStream fos = null; byte[] buf = new byte[2048]; int len = 0; try { is = response.body().byteStream(); final long total = response.body().contentLength(); Log.i(TAG, "total content Length: " + total); File dir = new File(MyApp.getDatabaseDirPath()); File file = new File(dir, mDownloadfile); fos = new FileOutputStream(file); while ((len = is.read(buf)) != -1) { fos.write(buf, 0, len); } fos.flush(); is.close(); fos.close(); // msg.what = MSG_DOWNLOAD_SUCCEED; // MyApp.showToast(MipcaActivityCapture.this, "下载数据库成功"); } catch (IOException e) { // msg.what = MSG_DOWNLOAD_FAILED; e.printStackTrace(); return false; } return true; // myHandler.sendMessage(msg); // MyApp.showToast(MipcaActivityCapture.this, "下载文件成功!"); }
@RequestMapping(value = "repo/{owner}/{repo}/readme", method = RequestMethod.GET) @ResponseBody public String readme( @PathVariable("owner") String owner, @PathVariable("repo") String repo, HttpServletRequest request) { GithubService githubService = (GithubService) request.getSession().getAttribute("githubService"); checkNotNull(githubService); JsonParser jsonParser = JsonParserFactory.getInstance(); String readmeUrl = README_URL.replace(":owner", owner).replace(":repo", repo); String download_url = jsonParser .parse(githubService.request(readmeUrl).getBody()) .getAsJsonObject() .get("download_url") .getAsString(); PegDownProcessor pegDown = new PegDownProcessor(Extensions.ALL); String readme = ""; Request readmeRequest = new Request.Builder().url(download_url).build(); Response response = null; try { response = client.newCall(readmeRequest).execute(); readme = response.body().string(); } catch (IOException e) { log.warning(e.getMessage()); } if (readme != null) { readme = pegDown.markdownToHtml(readme.toCharArray()); } Map map = new HashMap<>(); map.put("readme", readme); return JsonConstructFactory.getInstance().toJson(map); }
private String run(String url) throws IOException { client = new OkHttpClient(); Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); return response.body().string(); }
public GroupManagerResponse updateUser(UserDTO userDTO, String url, String token) throws GroupManagerClientException { OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(20, TimeUnit.SECONDS); client.setReadTimeout(20, TimeUnit.SECONDS); ObjectMapper objMapper = new ObjectMapper(); String jsonString; try { jsonString = objMapper.writeValueAsString(userDTO); System.out.println(jsonString); RequestBody body = RequestBody.create(JSON, jsonString); Request request = new Request.Builder().addHeader("Authorization", token).url(url).post(body).build(); Response response = client.newCall(request).execute(); System.out.println(response.isSuccessful()); GroupManagerResponse responseGroup = objMapper.readValue(response.body().byteStream(), GroupManagerResponse.class); return responseGroup; } catch (JsonGenerationException e) { throw new GroupManagerClientException("Failed to authenticate"); } catch (JsonMappingException e) { throw new GroupManagerClientException("Failed to authenticate"); } catch (IOException e) { e.printStackTrace(); throw new GroupManagerClientException("Failed to authenticate"); } }
private static FederationToken getTokenFromServer(String serverAddress) { String queryUrl = serverAddress + "/auth/stsSign"; String responseStr = null; try { OkHttpClient httpClient = new OkHttpClient(); Request request = new Request.Builder().url(queryUrl).build(); Response response = httpClient.newCall(request).execute(); responseStr = response.body().string(); } catch (IOException e) { e.printStackTrace(); } if (responseStr == null) { return null; } try { JSONObject jsonObject = new JSONObject(responseStr); String ak = jsonObject.getString("tempAK"); String sk = jsonObject.getString("tempSK"); String securityToken = jsonObject.getString("token"); long expireTime = jsonObject.getLong("expiration"); return new FederationToken(ak, sk, securityToken, expireTime); } catch (JSONException e) { e.printStackTrace(); } return null; }
private String sendPop(Transaction tx) { RequestBody requestBody = RequestBody.create(MediaType.parse("application/bitcoin-pop"), tx.toBytes()); URL url; try { url = new URL(popRequest.getP()); if (!"http".equals(url.getProtocol()) && !"https".equals(url.getProtocol())) { return "Invalid Url, expected protocol http or https: " + popRequest.getP(); } } catch (MalformedURLException e) { return "Invalid Url: " + popRequest.getP(); } Request request = new Request.Builder().url(url).post(requestBody).build(); OkHttpClient httpClient = new OkHttpClient(); if (_mbwManager.getTorMode() == ServerEndpointType.Types.ONLY_TOR && _mbwManager.getTorManager() != null) { httpClient = _mbwManager.getTorManager().setupClient(httpClient); } try { Response response = httpClient.newCall(request).execute(); if (response.isSuccessful()) { return response.body().string(); } else { return "Error occurred: " + response.code(); } } catch (IOException e) { return "Cannot communicate with server: " + e.getMessage(); } }
public static void main(String[] args) throws IOException { OkHttpClient client = new OkHttpClient(); final MediaType MEDIA_TYPE_TEXT = MediaType.parse("text/plain"); final String postBody = "Hello World"; RequestBody requestBody = new RequestBody() { @Override public MediaType contentType() { return MEDIA_TYPE_TEXT; } @Override public void writeTo(BufferedSink sink) throws IOException { sink.writeUtf8(postBody); } @Override public long contentLength() throws IOException { return postBody.length(); } }; Request request = new Request.Builder().url("http://www.baidu.com").post(requestBody).build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new IOException("服务器端错误: " + response); } System.out.println(response.body().string()); }
@Override public Response intercept(final Chain chain) throws IOException { long t1 = System.nanoTime(); final Request request = chain.request(); Log.v( NextClient.TAG, String.format( "[OkHttp Request] %s %s on %s%n", request.method(), request.url(), chain.connection())); if (mHeaders) { Log.v(NextClient.TAG, "[Request Headers] " + request.headers()); } final Response response = chain.proceed(request); long t2 = System.nanoTime(); Log.v( NextClient.TAG, String.format( "[OkHttp Response] %s %s (%s:%s) in %.1fms%n ", request.method(), request.url(), response.code(), response.message(), (t2 - t1) / 1e6d)); if (mHeaders) { Log.v(NextClient.TAG, "[Response Headers] " + response.headers()); } if (mBody) { Log.v(NextClient.TAG, "[OkHttp Response Body] " + responseToText(response)); } return response; }
/* * Enabled aggressive block sorting */ @Override public Request authenticateProxy(Proxy object, Response object2) throws IOException { List<Challenge> list = object2.challenges(); object2 = object2.request(); URL uRL = object2.url(); int n2 = 0; int n3 = list.size(); while (n2 < n3) { InetSocketAddress inetSocketAddress; Object object3 = list.get(n2); if ("Basic".equalsIgnoreCase(object3.getScheme()) && (object3 = java.net.Authenticator.requestPasswordAuthentication( (inetSocketAddress = (InetSocketAddress) object.address()).getHostName(), this.getConnectToInetAddress((Proxy) object, uRL), inetSocketAddress.getPort(), uRL.getProtocol(), object3.getRealm(), object3.getScheme(), uRL, Authenticator.RequestorType.PROXY)) != null) { object = Credentials.basic(object3.getUserName(), new String(object3.getPassword())); return object2.newBuilder().header("Proxy-Authorization", (String) object).build(); } ++n2; } return null; }
@Override protected ArrayList<Review> doInBackground(String... params) { ArrayList<Review> reviews = new ArrayList<>(); try { URL url = new URL(Constant.getReviewsUrl(movie.getId())); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); String responseJSONString = response.body().string(); if (response.isSuccessful()) { JSONObject responseJSON = new JSONObject(responseJSONString); JSONArray resultJSONArray = responseJSON.getJSONArray("results"); for (int i = 0; i < resultJSONArray.length(); i++) { JSONObject reviewJSON = resultJSONArray.getJSONObject(i); String author = reviewJSON.getString("author"); String content = reviewJSON.getString("content"); Review review = new Review(movie.getId(), author, content); reviews.add(review); } return reviews; } else { Log.v("response", "code not 200"); return null; } } catch (Exception e) { Log.v("response", e.toString()); return null; } }
public static String textToID(String bookName) { String ID = ""; OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(1000, TimeUnit.SECONDS); client.setReadTimeout(1000, TimeUnit.SECONDS); Request request = new Request.Builder() .url("https://hackingedu.chegg.com/hacking-edu/search?q=" + bookName) .get() .addHeader("accept", "application/json") .addHeader( "authorization", "Basic TXlPYUhWOUFtN01QdmxuSmJVVVV2SXZyaVBnYmVlQUE6MG1zQVFWbk1wemNS MXNjNA==") .addHeader("cache-control", "no-cache") // .addHeader("postman-token", "46e822fd-4a38-3db0-b60b-4bb26491f121") .build(); Response response = null; String fullResponse = ""; try { response = client.newCall(request).execute(); fullResponse = response.body().string(); // System.out.println(fullResponse); } catch (Exception e) { System.out.println(e); } // ID = response.result[0].responseContent.docs[0].id; String finalID = fullResponse.substring(fullResponse.indexOf("LBP"), fullResponse.indexOf("LBP") + 12); System.out.println( fullResponse.substring(fullResponse.indexOf("LBP"), fullResponse.indexOf("LBP") + 12)); return finalID; }
public byte[] byteArrayHttpClient(final String urlString) throws Exception { OkHttpClient client = null; if (client == null) { client = new OkHttpClient(); Cache responseCache = new Cache(CommonUtil.getImageSavePath(), 2 * 1024 * 1024); client.setCache(responseCache); client.setReadTimeout(30, java.util.concurrent.TimeUnit.SECONDS); client.setConnectTimeout(30, java.util.concurrent.TimeUnit.SECONDS); } FilterInputStream inputStream = getFromCache(urlString); if (inputStream != null) { return IOUtils.toByteArray(inputStream); } InputStream in = null; try { final String decodedUrl = URLDecoder.decode(urlString, "UTF-8"); final URL url = new URL(decodedUrl); final Request request = new Request.Builder().url(url).build(); final Response response = client.newCall(request).execute(); in = response.body().byteStream(); return IOUtils.toByteArray(in); } catch (final MalformedURLException e) { } catch (final OutOfMemoryError e) { } catch (final UnsupportedEncodingException e) { } catch (final IOException e) { } finally { if (in != null) { try { in.close(); } catch (final IOException ignored) { } } } return null; }
@Override protected EarthWallpaper doInBackground(Void... params) { Gson gson = new Gson(); OkHttpClient okHttpClient = new OkHttpClient(); String id; String requestUrl; if (useWallId == null) { id = IdUtils.getRandomId(); } else { id = useWallId; } requestUrl = ApiUtils.getApiUrl(id); try { Request request = new Request.Builder().url(requestUrl).build(); Response response = okHttpClient.newCall(request).execute(); if (!response.isSuccessful()) return null; EarthWallpaper wallpaper = gson.fromJson(response.body().charStream(), EarthWallpaper.class); if (wallpaper != null && wallpaper.getWallpaperId().equals(id)) return wallpaper; } catch (IOException io) { Log.d("AsyncLoader", "IOError: " + io.getLocalizedMessage()); } return null; }
/** * Get请求 同步 execute() * * @param url 地址 * @return 请求的字符串 */ public String run(String url) throws IOException { // 生成一个request,把url放进去 Request request = new Request.Builder().url(url).build(); // 执行request,并得到response Response response = client.newCall(request).execute(); // 把response中的body转化成string返回 return response.body().string(); }
@Override public Response intercept(Chain chain) throws IOException { String requestId = String.valueOf(mNextRequestId.getAndIncrement()); Request request = chain.request(); int requestSize = 0; if (mEventReporter.isEnabled()) { OkHttpInspectorRequest inspectorRequest = new OkHttpInspectorRequest(requestId, request); mEventReporter.requestWillBeSent(inspectorRequest); byte[] requestBody = inspectorRequest.body(); if (requestBody != null) { requestSize += requestBody.length; } } Response response; try { response = chain.proceed(request); } catch (IOException e) { if (mEventReporter.isEnabled()) { mEventReporter.httpExchangeFailed(requestId, e.toString()); } throw e; } if (mEventReporter.isEnabled()) { if (requestSize > 0) { mEventReporter.dataSent(requestId, requestSize, requestSize); } Connection connection = chain.connection(); mEventReporter.responseHeadersReceived( new OkHttpInspectorResponse(requestId, request, response, connection)); ResponseBody body = response.body(); MediaType contentType = null; InputStream responseStream = null; if (body != null) { contentType = body.contentType(); responseStream = body.byteStream(); } responseStream = mEventReporter.interpretResponseStream( requestId, contentType != null ? contentType.toString() : null, response.header("Content-Encoding"), responseStream, new DefaultResponseHandler(mEventReporter, requestId)); if (responseStream != null) { response = response.newBuilder().body(new ForwardingResponseBody(body, responseStream)).build(); } } return response; }
/** * Returns the value of the field corresponding to the {@code fieldName}, or null if there is no * such field. If the field has multiple values, the last value is returned. */ @Override public final String getHeaderField(String fieldName) { try { Response response = getResponse().getResponse(); return fieldName == null ? response.statusLine() : response.headers().get(fieldName); } catch (IOException e) { return null; } }
/** * 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(); T data = handleResponse(response, returnType); return new ApiResponse<T>(response.code(), response.headers().toMultimap(), data); } catch (IOException e) { throw new ApiException(e); } }
public static String dataFromResponse(Response response) { try { return response.body().string(); } catch (IOException e) { Log.w(Constants.LOG_TAG, "Exception while fetching data from " + response.toString()); e.printStackTrace(); return null; } }
@Override public final Map<String, List<String>> getHeaderFields() { try { Response response = getResponse().getResponse(); return OkHeaders.toMultimap(response.headers(), response.statusLine()); } catch (IOException e) { return Collections.emptyMap(); } }
protected WebResourceResponse toWebResource(Response response) throws IOException { if (response == null || !response.isSuccessful()) { return null; } String mimeType = response.header("Content-Type"); String charset = response.header("charset"); return new WebResourceResponse(mimeType, charset, response.body().byteStream()); }
private Response unzip(Response response) { while (!transparentGzip || !"gzip".equalsIgnoreCase(userResponse.header("Content-Encoding")) || response.body() == null) { return response; } p p1 = new p(response.body().source()); Headers headers = response.headers().newBuilder().removeAll("Content-Encoding").removeAll("Content-Length").build(); return response.newBuilder().headers(headers).body(new RealResponseBody(headers, r.a(p1))).build(); }
@Override public void run() { boolean success = false; Log.d(TAG, "feedback sending thread started"); try { final FormEncodingBuilder form = new FormEncodingBuilder(); for (Entry e : entries_) { form.add("timestamp[]", "" + e.timestamp); form.add("installationId[]", "" + getInstallationId()); form.add("feedback_id[]", "" + e.feedback_id); form.add("feedback_from_name[]", "" + e.feedback_from_name); form.add("feedback_from_email[]", "" + e.feedback_from_email); form.add("feedback_body[]", "" + e.feedback_body); form.add("package_name[]", "" + context_.getPackageName()); form.add("package_versionCode[]", "" + e.package_versionCode); form.add("build_product[]", "" + getBuildProduct()); form.add("build_device[]", "" + getBuildDevice()); form.add("build_model[]", "" + getBuildModel()); form.add("build_version_sdk[]", "" + e.build_version_sdk); } final Response resp = client .newCall( new Request.Builder() .url("https://alkitab-host.appspot.com/laban/submit") .post(form.build()) .build()) .execute(); final byte[] out = resp.body().bytes(); if (out.length >= 2 && out[0] == 'O' && out[1] == 'K') { success = true; } if (onSuccessListener_ != null) { onSuccessListener_.onSuccess(out); } if (success) { synchronized (FeedbackSender.this) { entries_.clear(); } save(); } } catch (IOException e) { Log.w(TAG, "when posting feedback", e); // $NON-NLS-1$ } finally { Log.d(TAG, "feedback sending thread ended. success = " + success); sending_ = false; } }
public static byte[] getSyncBytes(String url) throws SocketTimeoutException { Request request = new Request.Builder().url(url).build(); try { com.squareup.okhttp.Response response = httpClient.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); return response.body().bytes(); } catch (IOException ex) { ex.printStackTrace(); } return null; }
protected String doInBackground(URL... urls) { URL url = urls[0]; try { Request request = new Request.Builder().url(url).build(); Response response = HTTP_CLIENT.newCall(request).execute(); return response.body().string(); } catch (IOException ex) { Log.e(APP_NAME, "Could not retreive JSON from server:"); } return null; }
@Override public DeleteObjectResult parse(Response response) throws IOException { DeleteObjectResult result = new DeleteObjectResult(); try { result.setRequestId(response.header(OSSHeaders.OSS_HEADER_REQUEST_ID)); result.setStatusCode(response.code()); result.setResponseHeader(parseResponseHeader(response)); return result; } finally { safeCloseResponse(response); } }
private Response readNetworkResponse() { transport.finishRequest(); Response response1 = transport.readResponseHeaders().request(networkRequest).handshake(connection.getHandshake()).header(OkHeaders.SENT_MILLIS, Long.toString(sentRequestMillis)).header(OkHeaders.RECEIVED_MILLIS, Long.toString(System.currentTimeMillis())).build(); Response response = response1; if (!forWebSocket) { response = response1.newBuilder().body(transport.openResponseBody(response1)).build(); } Internal.instance.setProtocol(connection, response.protocol()); return response; }
public static String[] findSimilar(String idToGetRelated) { String IDofRelated = ""; OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url( "https://hackingedu.chegg.com/hacking-edu/catalog/relateditem/priced/getRelatedItems?catalogItemId=" + idToGetRelated) .get() .addHeader("accept", "application/json") .addHeader("content-type", "application/json") .addHeader( "authorization", "Basic TXlPYUhWOUFtN01QdmxuSmJVVVV2SXZyaVBnYmVlQUE6MG1zQVFWbk1wemNS MXNjNA==") .addHeader("cache-control", "no-cache") // .addHeader("postman-token", "2b21d3c9-023b-519e-4681-a7e20281879e") .build(); Response response = null; try { response = client.newCall(request).execute(); // System.out.println(response.toString()); } catch (Exception e) { System.out.println(e); } String myResponse = ""; try { myResponse = response.body().string(); } catch (Exception e) { System.out.println(e); } // System.out.println("MY RESPONSE " + myResponse); /*JSONObject jObject = new JSONObject(new String(myResponse)); JSONArray jArray = jObject.getJSONArray("result");*/ Object obj = JSONValue.parse(myResponse); JSONArray array = (JSONArray) obj; // System.out.println("ARRAY: " + array.toString()); String[] IDlist = new String[array.size()]; for (int i = 0; i < array.size(); i++) { IDlist[i] = (String) ((JSONObject) array.get(i)).get("catalogItemIdTo"); } // IDofRelated = myResponse; // String [] IDlist = new String [response.result.length]; // for(int i=0; i<response.result.length; i++){ // IDlist [i] = response.result[i].responseContent.docs[0].id; // } return IDlist; }
public static String getHtmlString(String url) { try { Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); return response.body().string(); } catch (Exception e) { XLog.d("win", "lllll" + e.toString()); return ""; } }