Java Examples for okhttp3.Request.Builder
The following java examples will help you to understand the usage of okhttp3.Request.Builder. These source code samples are taken from different open source projects.
Example 1
| Project: weixin4j-master File: OkHttpClient3.java View source code |
/**
* resolve Request.Headers
* */
protected void resolveHeaders(okhttp3.Request.Builder builder, HttpRequest request) {
com.foxinmy.weixin4j.http.HttpHeaders headers = request.getHeaders();
if (headers == null) {
headers = new HttpHeaders();
}
// Add default accept headers
if (!headers.containsKey(HttpHeaders.ACCEPT)) {
headers.set(HttpHeaders.ACCEPT, "*/*");
}
// Add default user agent
if (!headers.containsKey(HttpHeaders.USER_AGENT)) {
headers.set(HttpHeaders.USER_AGENT, "square/okhttp3");
}
for (Entry<String, List<String>> header : headers.entrySet()) {
if (HttpHeaders.COOKIE.equalsIgnoreCase(header.getKey())) {
builder.header(header.getKey(), StringUtil.join(header.getValue(), ';'));
} else {
for (String headerValue : header.getValue()) {
builder.header(header.getKey(), headerValue != null ? headerValue : "");
}
}
}
}Example 2
| Project: RxVolley-master File: OkHttpStack.java View source code |
@SuppressWarnings("deprecation")
private static void setConnectionParametersForRequest(okhttp3.Request.Builder builder, Request<?> request) throws IOException {
switch(request.getMethod()) {
case RxVolley.Method.GET:
builder.get();
break;
case RxVolley.Method.DELETE:
builder.delete();
break;
case RxVolley.Method.POST:
builder.post(createRequestBody(request));
break;
case RxVolley.Method.PUT:
builder.put(createRequestBody(request));
break;
case RxVolley.Method.HEAD:
builder.head();
break;
case RxVolley.Method.OPTIONS:
builder.method("OPTIONS", null);
break;
case RxVolley.Method.TRACE:
builder.method("TRACE", null);
break;
case RxVolley.Method.PATCH:
builder.patch(createRequestBody(request));
break;
default:
throw new IllegalStateException("Unknown method type.");
}
}Example 3
| Project: picasso-master File: NetworkRequestHandler.java View source code |
private static okhttp3.Request createRequest(Request request, int networkPolicy) {
CacheControl cacheControl = null;
if (networkPolicy != 0) {
if (NetworkPolicy.isOfflineOnly(networkPolicy)) {
cacheControl = CacheControl.FORCE_CACHE;
} else {
CacheControl.Builder builder = new CacheControl.Builder();
if (!NetworkPolicy.shouldReadFromDiskCache(networkPolicy)) {
builder.noCache();
}
if (!NetworkPolicy.shouldWriteToDiskCache(networkPolicy)) {
builder.noStore();
}
cacheControl = builder.build();
}
}
okhttp3.Request.Builder builder = new okhttp3.Request.Builder().url(request.uri.toString());
if (cacheControl != null) {
builder.cacheControl(cacheControl);
}
return builder.build();
}Example 4
| Project: openshift-restclient-java-master File: BasicChallangeHandlerTest.java View source code |
@Test
public void testHandleChallange() {
Builder builder = new Request.Builder().url("http://foo");
Request request = handler.handleChallange(builder).build();
String authorization = request.header(OpenShiftAuthenticator.PROPERTY_AUTHORIZATION);
assertTrue("Exp. auth to not be blank", StringUtils.isNotBlank(authorization));
assertTrue("Exp. auth to be basic", authorization.startsWith(OpenShiftAuthenticator.AUTHORIZATION_BASIC));
}Example 5
| Project: boardgamegeek4android-master File: CollectionTask.java View source code |
public void post() {
Request request = new Builder().url(GEEK_COLLECTION_URL).post(createForm(collectionItem)).build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
final String content = response.body().string();
if (content.startsWith(ERROR_DIV)) {
error = Html.fromHtml(content).toString().trim();
}
saveContent(content);
} else {
error = "Unsuccessful post: " + response.code();
}
} catch (IOException e) {
exception = e;
}
}Example 6
| Project: CanvasAPI-master File: CanvasOkClient.java View source code |
static com.squareup.okhttp.Request createRequest(Request request) {
com.squareup.okhttp.Request.Builder builder = new com.squareup.okhttp.Request.Builder().url(request.getUrl()).method(request.getMethod(), createRequestBody(request.getBody()));
List<Header> headers = request.getHeaders();
for (int i = 0, size = headers.size(); i < size; i++) {
Header header = headers.get(i);
String value = header.getValue();
if (value == null)
value = "";
builder.addHeader(header.getName(), value);
}
return builder.build();
}Example 7
| Project: RedReader-master File: OKHTTPBackend.java View source code |
@Override
public Request prepareRequest(final Context context, final RequestDetails details) {
final com.squareup.okhttp.Request.Builder builder = new com.squareup.okhttp.Request.Builder();
builder.header("User-Agent", Constants.ua(context));
final List<PostField> postFields = details.getPostFields();
if (postFields != null) {
builder.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), PostField.encodeList(postFields)));
} else {
builder.get();
}
builder.url(details.getUrl().toString());
builder.cacheControl(CacheControl.FORCE_NETWORK);
final AtomicReference<Call> callRef = new AtomicReference<>();
return new Request() {
public void executeInThisThread(final Listener listener) {
final Call call = mClient.newCall(builder.build());
callRef.set(call);
try {
final Response response;
try {
response = call.execute();
} catch (IOException e) {
listener.onError(CacheRequest.REQUEST_FAILURE_CONNECTION, e, null);
return;
}
final int status = response.code();
if (status == 200 || status == 202) {
final ResponseBody body = response.body();
final InputStream bodyStream;
final Long bodyBytes;
if (body != null) {
bodyStream = body.byteStream();
bodyBytes = body.contentLength();
} else {
// TODO error
bodyStream = null;
bodyBytes = null;
}
final String contentType = response.header("Content-Type");
listener.onSuccess(contentType, bodyBytes, bodyStream);
} else {
listener.onError(CacheRequest.REQUEST_FAILURE_REQUEST, null, status);
}
} catch (Throwable t) {
listener.onError(CacheRequest.REQUEST_FAILURE_CONNECTION, t, null);
}
}
@Override
public void cancel() {
final Call call = callRef.getAndSet(null);
if (call != null) {
call.cancel();
}
}
@Override
public void addHeader(final String name, final String value) {
builder.addHeader(name, value);
}
};
}Example 8
| Project: PkRSS-master File: OkHttp3Downloader.java View source code |
@Override
public String execute(Request request) throws IllegalArgumentException, IOException {
// Invalid URLs are a big no no
if (request.url == null || request.url.isEmpty()) {
throw new IllegalArgumentException("Invalid URL!");
}
// Start tracking download time
long time = System.currentTimeMillis();
// Empty response string placeholder
String responseStr;
// Handle cache
int maxCacheAge = request.skipCache ? 0 : cacheMaxAge;
// Build proper URL
String requestUrl = toUrl(request);
// Build the OkHttp request
okhttp3.Request httpRequest = new okhttp3.Request.Builder().addHeader("Cache-Control", "public, max-age=" + maxCacheAge).url(requestUrl).build();
try {
// Execute the built request and log its data
log("Making a request to " + requestUrl + (request.skipCache ? " [SKIP-CACHE]" : " [MAX-AGE " + maxCacheAge + "]"));
Response response = client.newCall(httpRequest).execute();
// Was this retrieved from cache?
if (response.cacheResponse() != null) {
log("Response retrieved from cache");
}
// Convert response body to a string
responseStr = response.body().string();
log(TAG, "Request download took " + (System.currentTimeMillis() - time) + "ms", Log.INFO);
} catch (Exception e) {
log("Error executing/reading http request!", Log.ERROR);
e.printStackTrace();
throw new IOException(e.getMessage());
}
return responseStr;
}Example 9
| Project: engine.io-client-java-master File: PollingXHR.java View source code |
public void create() {
final Request self = this;
logger.fine(String.format("xhr open %s: %s", this.method, this.uri));
Map<String, List<String>> headers = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER);
if ("POST".equals(this.method)) {
headers.put("Content-type", new LinkedList<String>(Collections.singletonList(BINARY_CONTENT_TYPE)));
}
self.onRequestHeaders(headers);
logger.fine(String.format("sending xhr with url %s | data %s", this.uri, Arrays.toString(this.data)));
okhttp3.Request.Builder requestBuilder = new okhttp3.Request.Builder();
for (Map.Entry<String, List<String>> header : headers.entrySet()) {
for (String v : header.getValue()) {
requestBuilder.addHeader(header.getKey(), v);
}
}
okhttp3.Request request = requestBuilder.url(HttpUrl.parse(self.uri)).method(self.method, (self.data != null) ? RequestBody.create(MediaType.parse(BINARY_CONTENT_TYPE), self.data) : null).build();
requestCall = callFactory.newCall(request);
requestCall.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
self.onError(e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
self.response = response;
self.onResponseHeaders(response.headers().toMultimap());
if (response.isSuccessful()) {
self.onLoad();
} else {
self.onError(new IOException(Integer.toString(response.code())));
}
}
});
}Example 10
| Project: round-java-master File: Client.java View source code |
public String performRawRequest(String url, ActionSpec actionSpec, JsonElement requestBody) throws IOException, UnexpectedStatusCodeException {
com.squareup.okhttp.Request.Builder builder = new Request.Builder().url(url);
RequestBody body = null;
if (requestBody != null)
body = RequestBody.create(null, requestBody.toString());
builder.method(actionSpec.method(), body);
String authorization = null;
for (String scheme : actionSpec.request().authorizations()) {
if (authorizer.isAuthorized(scheme)) {
authorization = authorizer.getCredentials(scheme);
break;
}
}
if (authorization != null)
builder.header(AUTHORIZATION_HEADER, authorization);
if (actionSpec.response().type() != null)
builder.header(ACCEPT_HEADER, actionSpec.response().type());
if (actionSpec.request().type() != null)
builder.header(CONTENT_TYPE_HEADER, actionSpec.request().type());
Request request = builder.build();
Response response = httpClient.newCall(request).execute();
int statusCode = response.code();
String responseContent = response.body().string();
if (statusCode != actionSpec.response().status())
throw new UnexpectedStatusCodeException(responseContent, statusCode, response);
return responseContent;
}Example 11
| Project: sonarqube-master File: CeHttpClient.java View source code |
@Override
public Void call(String url) throws Exception {
okhttp3.Request request = new okhttp3.Request.Builder().post(RequestBody.create(null, new byte[0])).url(url + "?level=" + newLogLevel.name()).build();
okhttp3.Response response = new OkHttpClient().newCall(request).execute();
if (response.code() != 200) {
throw new IOException(String.format("Failed to change log level in Compute Engine. Code was '%s' and response was '%s' for url '%s'", response.code(), response.body().string(), url));
}
return null;
}