本文整理匯總了Java中com.squareup.okhttp.Request.Builder方法的典型用法代碼示例。如果您正苦於以下問題:Java Request.Builder方法的具體用法?Java Request.Builder怎麽用?Java Request.Builder使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類com.squareup.okhttp.Request
的用法示例。
在下文中一共展示了Request.Builder方法的11個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: doInBackground
import com.squareup.okhttp.Request; //導入方法依賴的package包/類
@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;
}
示例2: networkRequest
import com.squareup.okhttp.Request; //導入方法依賴的package包/類
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();
}
示例3: init
import com.squareup.okhttp.Request; //導入方法依賴的package包/類
@PostConstruct
public void init() throws IOException {
Map<String, String> headers = new HashMap<>();
String[] localVarAuthNames = new String[] { "BearerToken" };
List<Pair> queryParams = new ArrayList<>();
kc.updateParamsForAuth(localVarAuthNames, queryParams, headers);
Request.Builder builder = new Request.Builder().url(kc.getBasePath() + "/version");
for (Map.Entry<String, String> header : headers.entrySet())
builder.addHeader(header.getKey(), header.getValue());
Call call = kc.getHttpClient().newCall(builder.get().build());
ResponseBody res = call.execute().body();
Map version = om.readValue(res.byteStream(), Map.class);
String status = (String)version.get("status");
if ("Failure".equals(status))
throw new RuntimeException("/version returned " + status);
major = Integer.parseInt((String) version.get("major"));
minor = Integer.parseInt((String) version.get("minor"));
}
示例4: handleMessage
import com.squareup.okhttp.Request; //導入方法依賴的package包/類
@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;
}
}
示例5: newHttpEngine
import com.squareup.okhttp.Request; //導入方法依賴的package包/類
private HttpEngine newHttpEngine(String method, StreamAllocation streamAllocation,
RetryableSink requestBody, Response priorResponse) throws
MalformedURLException, UnknownHostException {
Request.Builder builder = new Request.Builder().url(Internal.instance.getHttpUrlChecked
(getURL().toString())).method(method, HttpMethod.requiresRequestBody(method) ?
EMPTY_REQUEST_BODY : null);
Headers headers = this.requestHeaders.build();
int size = headers.size();
for (int i = 0; i < size; i++) {
builder.addHeader(headers.name(i), headers.value(i));
}
boolean bufferRequestBody = false;
if (HttpMethod.permitsRequestBody(method)) {
if (this.fixedContentLength != -1) {
builder.header("Content-Length", Long.toString(this.fixedContentLength));
} else if (this.chunkLength > 0) {
builder.header("Transfer-Encoding", "chunked");
} else {
bufferRequestBody = true;
}
if (headers.get("Content-Type") == null) {
builder.header("Content-Type", Client.FormMime);
}
}
if (headers.get(Network.USER_AGENT) == null) {
builder.header(Network.USER_AGENT, defaultUserAgent());
}
Request request = builder.build();
OkHttpClient engineClient = this.client;
if (!(Internal.instance.internalCache(engineClient) == null || getUseCaches())) {
engineClient = this.client.clone().setCache(null);
}
return new HttpEngine(engineClient, request, bufferRequestBody, true, false,
streamAllocation, requestBody, priorResponse);
}
示例6: buildRequest
import com.squareup.okhttp.Request; //導入方法依賴的package包/類
private Request buildRequest(String url, HttpMethodType methodType, Map<String, Object> params) {
Request.Builder builder = new Request.Builder()
.url(url);
if (methodType == HttpMethodType.POST) {
RequestBody body = builderFormData(params);
builder.post(body);
} else if (methodType == HttpMethodType.GET) {
url = buildUrlParams(url, params);
builder.url(url);
builder.get();
}
return builder.build();
}
示例7: buildRequest
import com.squareup.okhttp.Request; //導入方法依賴的package包/類
public Request buildRequest(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
updateParamsForAuth(authNames, queryParams, headerParams);
final String url = buildUrl(path, queryParams);
final Request.Builder reqBuilder = new Request.Builder().url(url);
processHeaderParams(headerParams, reqBuilder);
String contentType = (String) headerParams.get("Content-Type");
// ensuring a default content type
if (contentType == null) {
contentType = "application/json";
}
RequestBody reqBody;
if (!HttpMethod.permitsRequestBody(method)) {
reqBody = null;
} else if ("application/x-www-form-urlencoded".equals(contentType)) {
reqBody = buildRequestBodyFormEncoding(formParams);
} else if ("multipart/form-data".equals(contentType)) {
reqBody = buildRequestBodyMultipart(formParams);
} else if (body == null) {
if ("DELETE".equals(method)) {
// allow calling DELETE without sending a request body
reqBody = null;
} else {
// use an empty request body (for POST, PUT and PATCH)
reqBody = RequestBody.create(MediaType.parse(contentType), "");
}
} else {
reqBody = serialize(body, contentType);
}
Request request = null;
if(progressRequestListener != null && reqBody != null) {
ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener);
request = reqBuilder.method(method, progressRequestBody).build();
} else {
request = reqBuilder.method(method, reqBody).build();
}
return request;
}
示例8: buildCall
import com.squareup.okhttp.Request; //導入方法依賴的package包/類
/**
* Build HTTP call with the given options.
*
* @param path The sub-path of the HTTP URL
* @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE"
* @param queryParams The query parameters
* @param body The request body object
* @param headerParams The header parameters
* @param formParams The form parameters
* @param authNames The authentications to apply
* @param progressRequestListener Progress request listener
* @return The HTTP call
* @throws ApiException If fail to serialize the request body object
*/
public Call buildCall(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
updateParamsForAuth(authNames, queryParams, headerParams);
final String url = buildUrl(path, queryParams);
final Request.Builder reqBuilder = new Request.Builder().url(url);
processHeaderParams(headerParams, reqBuilder);
String contentType = (String) headerParams.get("Content-Type");
// ensuring a default content type
if (contentType == null) {
contentType = "application/json";
}
RequestBody reqBody;
if (!HttpMethod.permitsRequestBody(method)) {
reqBody = null;
} else if ("application/x-www-form-urlencoded".equals(contentType)) {
reqBody = buildRequestBodyFormEncoding(formParams);
} else if ("multipart/form-data".equals(contentType)) {
reqBody = buildRequestBodyMultipart(formParams);
} else if (body == null) {
if ("DELETE".equals(method)) {
// allow calling DELETE without sending a request body
reqBody = null;
} else {
// use an empty request body (for POST, PUT and PATCH)
reqBody = RequestBody.create(MediaType.parse(contentType), "");
}
} else {
reqBody = serialize(body, contentType);
}
Request request = null;
if(progressRequestListener != null && reqBody != null) {
ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener);
request = reqBuilder.method(method, progressRequestBody).build();
} else {
request = reqBuilder.method(method, reqBody).build();
}
return httpClient.newCall(request);
}
示例9: flush
import com.squareup.okhttp.Request; //導入方法依賴的package包/類
@Override
public void flush() throws TTransportException {
Util.closeQuietly(mResponseBody);
mResponseBody = null;
RequestBody requestBody = new RequestBody() {
@Override
public MediaType contentType() {
if (mHeaders != null && mHeaders.containsKey("Content-Type")) {
return MediaType.parse(mHeaders.get("Content-Type"));
} else {
return MEDIA_TYPE_THRIFT;
}
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
sink.write(mByteStore.getData(), 0, mByteStore.getBytesWritten());
}
};
try {
Request.Builder builder = new Request.Builder()
.url(mUrl)
.post(requestBody);
if (mHeaders != null) {
for (String name : mHeaders.keySet()) {
builder.header(name, mHeaders.get(name));
}
}
Response response = mHttpClient.newCall(builder.build()).execute();
if (response.code() != 200) {
throw new TTransportException("HTTP Response code: " + response.code() + ", message " + response.message());
}
mResponseBody = response.body().byteStream();
} catch (Exception e) {
throw new TTransportException(e);
} finally {
try {
mByteStore.reset();
} catch (IOException ignored) {
}
}
}
示例10: onActivityCreated
import com.squareup.okhttp.Request; //導入方法依賴的package包/類
@Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
log.debug("querying \"{}\"...", versionUrl);
final Request.Builder request = new Request.Builder();
request.url(versionUrl);
request.header("Accept-Charset", "utf-8");
final String userAgent = application.httpUserAgent();
if (userAgent != null)
request.header("User-Agent", userAgent);
final Call call = Constants.HTTP_CLIENT.newCall(request.build());
backgroundHandler.post(new Runnable() {
@Override
public void run() {
boolean abort = false;
try {
final Response response = call.execute();
if (response.isSuccessful()) {
final long serverTime = response.headers().getDate("Date").getTime();
try (final BufferedReader reader = new BufferedReader(response.body().charStream())) {
abort = handleServerTime(serverTime);
while (true) {
final String line = reader.readLine();
if (line == null)
break;
if (line.charAt(0) == '#')
continue;
final Splitter splitter = Splitter.on('=').trimResults();
final Iterator<String> split = splitter.split(line).iterator();
if (!split.hasNext())
continue;
final String key = split.next();
if (!split.hasNext()) {
abort = handleLine(key);
if (abort)
break;
continue;
}
final String value = split.next();
if (!split.hasNext()) {
abort = handleProperty(key, value);
if (abort)
break;
continue;
}
log.info("Ignoring line: {}", line);
}
}
}
} catch (final Exception x) {
handleException(x);
}
if (!abort)
handleCatchAll();
}
});
}
示例11: fetchEvernoteUrl
import com.squareup.okhttp.Request; //導入方法依賴的package包/類
/**
* Fetches the URL with the current authentication token as cookie in the header.
*
* <br>
* <br>
*
* <b>Pay attention</b> to which URLs you are sending the authentication token. It's better to
* verify the host first.
*
* @param url The URL which should be opened.
* @return The raw response.
*/
public Response fetchEvernoteUrl(String url) throws IOException {
Request.Builder requestBuilder = new Request.Builder()
.url(url)
.addHeader("Cookie", mAuthHeader)
.get();
return mHttpClient.newCall(requestBuilder.build()).execute();
}