use of com.squareup.okhttp.Request in project hale by halestudio.
the class ProjectStoreHelper method executePlainTextCallWithFeedback.
/**
* Execute a REST call with the content type <code>text/plain; charset=utf-8
* </code>
*
* @param method HTTP method (POST, PUT)
* @param path REST path (without base path)
* @param body The plain text bdoy
* @param basePath The REST base path
* @param apiKey The API key
* @return the feedback
* @throws HaleConnectException thrown on any API error
*/
public static Feedback executePlainTextCallWithFeedback(String method, String path, String body, BasePathResolver basePath, String apiKey) throws HaleConnectException {
ApiClient apiClient = ProjectStoreHelper.getApiClient(basePath, apiKey);
OkHttpClient httpClient = apiClient.getHttpClient();
String url = apiClient.buildUrl(path, null);
Request.Builder reqBuilder = new Request.Builder().url(url);
Map<String, String> headerParams = new HashMap<String, String>();
apiClient.updateParamsForAuth(new String[] { "bearer" }, null, headerParams);
apiClient.processHeaderParams(headerParams, reqBuilder);
RequestBody reqBody = RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), body);
Request request = reqBuilder.method(method, reqBody).build();
Call call = httpClient.newCall(request);
Feedback feedback;
try {
ApiResponse<Feedback> resp = apiClient.execute(call, new TypeToken<Feedback>() {
}.getType());
feedback = resp.getData();
} catch (com.haleconnect.api.projectstore.v1.ApiException e) {
throw new HaleConnectException(e.getMessage(), e);
}
return feedback;
}
use of com.squareup.okhttp.Request in project qksms by moezbhatti.
the class MmsHttpClient method openConnection.
/**
* Open an HTTP connection
*
* TODO: The following code is borrowed from android.net.Network.openConnection
* Once that method supports proxy, we should use that instead
* Also we should remove the associated HostResolver and ConnectionPool from
* MmsNetworkManager
*
* @param url The URL to connect to
* @param proxy The proxy to use
* @return The opened HttpURLConnection
* @throws MalformedURLException If URL is malformed
*/
private HttpURLConnection openConnection(URL url, final Proxy proxy) throws MalformedURLException {
final String protocol = url.getProtocol();
OkHttpClient okHttpClient;
if (protocol.equals("http")) {
okHttpClient = new OkHttpClient();
okHttpClient.setFollowRedirects(false);
okHttpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
okHttpClient.setProxySelector(new ProxySelector() {
@Override
public List<Proxy> select(URI uri) {
if (proxy != null) {
return Arrays.asList(proxy);
} else {
return new ArrayList<Proxy>();
}
}
@Override
public void connectFailed(URI uri, SocketAddress address, IOException failure) {
}
});
okHttpClient.setAuthenticator(new com.squareup.okhttp.Authenticator() {
@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {
return null;
}
@Override
public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
return null;
}
});
okHttpClient.setConnectionSpecs(Arrays.asList(ConnectionSpec.CLEARTEXT));
okHttpClient.setConnectionPool(new ConnectionPool(3, 60000));
okHttpClient.setSocketFactory(SocketFactory.getDefault());
Internal.instance.setNetwork(okHttpClient, mHostResolver);
if (proxy != null) {
okHttpClient.setProxy(proxy);
}
return new HttpURLConnectionImpl(url, okHttpClient);
} else if (protocol.equals("https")) {
okHttpClient = new OkHttpClient();
okHttpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();
okHttpClient.setHostnameVerifier(verifier);
okHttpClient.setSslSocketFactory(HttpsURLConnection.getDefaultSSLSocketFactory());
okHttpClient.setProxySelector(new ProxySelector() {
@Override
public List<Proxy> select(URI uri) {
return Arrays.asList(proxy);
}
@Override
public void connectFailed(URI uri, SocketAddress address, IOException failure) {
}
});
okHttpClient.setAuthenticator(new com.squareup.okhttp.Authenticator() {
@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {
return null;
}
@Override
public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
return null;
}
});
okHttpClient.setConnectionSpecs(Arrays.asList(ConnectionSpec.CLEARTEXT));
okHttpClient.setConnectionPool(new ConnectionPool(3, 60000));
Internal.instance.setNetwork(okHttpClient, mHostResolver);
return new HttpsURLConnectionImpl(url, okHttpClient);
} else {
throw new MalformedURLException("Invalid URL or unrecognized protocol " + protocol);
}
}
use of com.squareup.okhttp.Request in project QuickAndroid by ImKarl.
the class OkHttpCacheHelper method getResponse.
private static Response getResponse(OkHttpClient client, Request request) throws IOException {
// Copy body metadata to the appropriate request headers.
RequestBody body = request.body();
if (body != null) {
Request.Builder requestBuilder = request.newBuilder();
MediaType contentType = body.contentType();
if (contentType != null) {
requestBuilder.header("Content-Type", contentType.toString());
}
long contentLength = body.contentLength();
if (contentLength != -1) {
requestBuilder.header("Content-Length", Long.toString(contentLength));
requestBuilder.removeHeader("Transfer-Encoding");
} else {
requestBuilder.header("Transfer-Encoding", "chunked");
requestBuilder.removeHeader("Content-Length");
}
request = requestBuilder.build();
}
copyWithDefaults(client);
// Create the initial HTTP engine. Retries and redirects need new engine
// for each attempt.
HttpEngine engine = new HttpEngine(client, request, false, false, false, null, null, null, null);
int followUpCount = 0;
while (true) {
try {
engine.sendRequest();
engine.readResponse();
} catch (RequestException e) {
// The attempt to interpret the request failed. Give up.
throw e.getCause();
} catch (RouteException e) {
// The attempt to connect via a route failed. The request will
// not have been sent.
HttpEngine retryEngine = engine.recover(e);
if (retryEngine != null) {
engine = retryEngine;
continue;
}
// Give up; recovery is not possible.
throw e.getLastConnectException();
} catch (IOException e) {
// An attempt to communicate with a server failed. The request
// may have been sent.
HttpEngine retryEngine = engine.recover(e, null);
if (retryEngine != null) {
engine = retryEngine;
continue;
}
// Give up; recovery is not possible.
throw e;
}
Response response = engine.getResponse();
Request followUp = engine.followUpRequest();
if (followUp == null) {
return response;
}
if (++followUpCount > MAX_FOLLOW_UPS) {
throw new ProtocolException("Too many follow-up requests: " + followUpCount);
}
if (!engine.sameConnection(followUp.httpUrl())) {
engine.releaseConnection();
}
Connection connection = engine.close();
request = followUp;
engine = new HttpEngine(client, request, false, false, false, connection, null, null, response);
}
}
use of com.squareup.okhttp.Request in project QuickAndroid by ImKarl.
the class OkHttp method loadSync.
/**
* 同步请求
*
* @param method
* @param url
* @param params
* @param listener
* @param <T>
*/
public <T> void loadSync(QAHttpMethod method, final String url, QARequestParams params, final QAHttpCallback<T> listener) {
final Request request = createRequest(method, url, params, listener);
if (request == null) {
return;
}
if (params != null && params.isPreLoad()) {
// 缓存加载
preLoad(url, params, request, listener);
}
// 网络加载
try {
Response response = mOkHttpClient.newCall(request).execute();
handlerResponse(url, params, response, listener);
} catch (Throwable e) {
sendFailedCallback(url, e, listener);
}
}
use of com.squareup.okhttp.Request in project QuickAndroid by ImKarl.
the class OkHttp method createRequest.
private <T> Request createRequest(QAHttpMethod method, String url, QARequestParams params, final QAHttpCallback<T> listener) {
if (method == null) {
method = QAHttpMethod.GET;
}
final String finalUrl = url;
if (method == QAHttpMethod.GET) {
url = parseGetUrl(url, params != null ? params.getParams() : null);
params = null;
} else {
if (params == null) {
params = new QARequestParams();
}
}
Request.Builder builder = new Request.Builder();
try {
builder.url(url);
} catch (final Exception e) {
sendFailedCallback(finalUrl, e, listener);
return null;
}
// 强制使用缓存
builder.cacheControl(CacheControl.FORCE_CACHE);
// header
Headers.Builder headerBuilder = new Headers.Builder();
if (params != null && !params.getHeaders().isEmpty()) {
for (Entry<String, String> entry : params.getHeaders().entrySet()) {
headerBuilder.add(entry.getKey(), entry.getValue());
}
}
builder.headers(headerBuilder.build());
// param
RequestBody requestBody = null;
if (params != null) {
if (!TextUtils.isEmpty(params.getBody())) {
requestBody = RequestBody.create(MEDIA_TYPE_TEXT, params.getBody());
} else {
try {
MultipartBuilder paramBuilder = new MultipartBuilder();
if (params != null && !params.getParams().isEmpty()) {
for (Entry<String, List<Part>> entry : params.getParams().entrySet()) {
String name = entry.getKey();
List<Part> parts = entry.getValue();
if (parts != null && !parts.isEmpty()) {
for (Part part : parts) {
paramBuilder.addPart(part.header(), part.body());
}
}
}
}
requestBody = paramBuilder.build();
} catch (IllegalStateException e) {
requestBody = new FormEncodingBuilder().build();
}
}
}
builder.method(method.name(), requestBody == null ? null : new ProgressRequestBody(requestBody, new OnProgressListener() {
@Override
public void onProgress(long currentBytes, long contentLength) {
// 上传进度
sendProgressCallback(finalUrl, currentBytes, contentLength, QAHttpAction.REQUEST, listener);
}
}));
final Request request = builder.build();
mOnProgressListeners.put(request, new OnProgressListener() {
@Override
public void onProgress(long currentBytes, long contentLength) {
// 下载进度
sendProgressCallback(finalUrl, currentBytes, contentLength, QAHttpAction.RESPONSE, listener);
}
});
return request;
}
Aggregations