use of okhttp3.RequestBody in project Fast-Android-Networking by amitshekhariitbhu.
the class InternalNetworking method performSimpleRequest.
public static Response performSimpleRequest(ANRequest request) throws ANError {
Request okHttpRequest;
Response okHttpResponse;
try {
Request.Builder builder = new Request.Builder().url(request.getUrl());
addHeadersToRequestBuilder(builder, request);
RequestBody requestBody = null;
switch(request.getMethod()) {
case GET:
{
builder = builder.get();
break;
}
case POST:
{
requestBody = request.getRequestBody();
builder = builder.post(requestBody);
break;
}
case PUT:
{
requestBody = request.getRequestBody();
builder = builder.put(requestBody);
break;
}
case DELETE:
{
requestBody = request.getRequestBody();
builder = builder.delete(requestBody);
break;
}
case HEAD:
{
builder = builder.head();
break;
}
case PATCH:
{
requestBody = request.getRequestBody();
builder = builder.patch(requestBody);
break;
}
}
if (request.getCacheControl() != null) {
builder.cacheControl(request.getCacheControl());
}
okHttpRequest = builder.build();
if (request.getOkHttpClient() != null) {
request.setCall(request.getOkHttpClient().newBuilder().cache(sHttpClient.cache()).build().newCall(okHttpRequest));
} else {
request.setCall(sHttpClient.newCall(okHttpRequest));
}
final long startTime = System.currentTimeMillis();
final long startBytes = TrafficStats.getTotalRxBytes();
okHttpResponse = request.getCall().execute();
final long timeTaken = System.currentTimeMillis() - startTime;
if (okHttpResponse.cacheResponse() == null) {
final long finalBytes = TrafficStats.getTotalRxBytes();
final long diffBytes;
if (startBytes == TrafficStats.UNSUPPORTED || finalBytes == TrafficStats.UNSUPPORTED) {
diffBytes = okHttpResponse.body().contentLength();
} else {
diffBytes = finalBytes - startBytes;
}
ConnectionClassManager.getInstance().updateBandwidth(diffBytes, timeTaken);
Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, (requestBody != null && requestBody.contentLength() != 0) ? requestBody.contentLength() : -1, okHttpResponse.body().contentLength(), false);
} else if (request.getAnalyticsListener() != null) {
if (okHttpResponse.networkResponse() == null) {
Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, 0, 0, true);
} else {
Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, (requestBody != null && requestBody.contentLength() != 0) ? requestBody.contentLength() : -1, 0, true);
}
}
} catch (IOException ioe) {
throw new ANError(ioe);
}
return okHttpResponse;
}
use of okhttp3.RequestBody in project Fast-Android-Networking by amitshekhariitbhu.
the class ANRequest method getMultiPartRequestBody.
public RequestBody getMultiPartRequestBody() {
MultipartBody.Builder builder = new MultipartBody.Builder().setType((customMediaType == null) ? MultipartBody.FORM : customMediaType);
try {
for (HashMap.Entry<String, String> entry : mMultiPartParameterMap.entrySet()) {
builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + entry.getKey() + "\""), RequestBody.create(null, entry.getValue()));
}
for (HashMap.Entry<String, File> entry : mMultiPartFileMap.entrySet()) {
String fileName = entry.getValue().getName();
RequestBody fileBody = RequestBody.create(MediaType.parse(Utils.getMimeType(fileName)), entry.getValue());
builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + entry.getKey() + "\"; filename=\"" + fileName + "\""), fileBody);
}
} catch (Exception e) {
e.printStackTrace();
}
return builder.build();
}
use of okhttp3.RequestBody in project okhttp by square.
the class InterceptorTest method networkInterceptorsCanChangeRequestMethodFromGetToPost.
@Test
public void networkInterceptorsCanChangeRequestMethodFromGetToPost() throws Exception {
server.enqueue(new MockResponse());
Interceptor interceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = RequestBody.create(mediaType, "abc");
return chain.proceed(originalRequest.newBuilder().method("POST", body).header("Content-Type", mediaType.toString()).header("Content-Length", Long.toString(body.contentLength())).build());
}
};
client = client.newBuilder().addNetworkInterceptor(interceptor).build();
Request request = new Request.Builder().url(server.url("/")).get().build();
client.newCall(request).execute();
RecordedRequest recordedRequest = server.takeRequest();
assertEquals("POST", recordedRequest.getMethod());
assertEquals("abc", recordedRequest.getBody().readUtf8());
}
use of okhttp3.RequestBody in project okhttp by square.
the class CallTest method reusedSinksGetIndependentTimeoutInstances.
@Test
public void reusedSinksGetIndependentTimeoutInstances() throws Exception {
server.enqueue(new MockResponse());
server.enqueue(new MockResponse());
// Call 1: set a deadline on the request body.
RequestBody requestBody1 = new RequestBody() {
@Override
public MediaType contentType() {
return MediaType.parse("text/plain");
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
sink.writeUtf8("abc");
sink.timeout().deadline(5, TimeUnit.SECONDS);
}
};
Request request1 = new Request.Builder().url(server.url("/")).method("POST", requestBody1).build();
Response response1 = client.newCall(request1).execute();
assertEquals(200, response1.code());
// Call 2: check for the absence of a deadline on the request body.
RequestBody requestBody2 = new RequestBody() {
@Override
public MediaType contentType() {
return MediaType.parse("text/plain");
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
assertFalse(sink.timeout().hasDeadline());
sink.writeUtf8("def");
}
};
Request request2 = new Request.Builder().url(server.url("/")).method("POST", requestBody2).build();
Response response2 = client.newCall(request2).execute();
assertEquals(200, response2.code());
// Use sequence numbers to confirm the connection was pooled.
assertEquals(0, server.takeRequest().getSequenceNumber());
assertEquals(1, server.takeRequest().getSequenceNumber());
}
use of okhttp3.RequestBody in project okhttp by square.
the class RetryAndFollowUpInterceptor method followUpRequest.
/**
* Figures out the HTTP request to make in response to receiving {@code userResponse}. This will
* either add authentication headers, follow redirects or handle a client request timeout. If a
* follow-up is either unnecessary or not applicable, this returns null.
*/
private Request followUpRequest(Response userResponse) throws IOException {
if (userResponse == null)
throw new IllegalStateException();
Connection connection = streamAllocation.connection();
Route route = connection != null ? connection.route() : null;
int responseCode = userResponse.code();
final String method = userResponse.request().method();
switch(responseCode) {
case HTTP_PROXY_AUTH:
Proxy selectedProxy = route != null ? route.proxy() : client.proxy();
if (selectedProxy.type() != Proxy.Type.HTTP) {
throw new ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy");
}
return client.proxyAuthenticator().authenticate(route, userResponse);
case HTTP_UNAUTHORIZED:
return client.authenticator().authenticate(route, userResponse);
case HTTP_PERM_REDIRECT:
case HTTP_TEMP_REDIRECT:
// or HEAD, the user agent MUST NOT automatically redirect the request"
if (!method.equals("GET") && !method.equals("HEAD")) {
return null;
}
// fall-through
case HTTP_MULT_CHOICE:
case HTTP_MOVED_PERM:
case HTTP_MOVED_TEMP:
case HTTP_SEE_OTHER:
// Does the client allow redirects?
if (!client.followRedirects())
return null;
String location = userResponse.header("Location");
if (location == null)
return null;
HttpUrl url = userResponse.request().url().resolve(location);
// Don't follow redirects to unsupported protocols.
if (url == null)
return null;
// If configured, don't follow redirects between SSL and non-SSL.
boolean sameScheme = url.scheme().equals(userResponse.request().url().scheme());
if (!sameScheme && !client.followSslRedirects())
return null;
// Most redirects don't include a request body.
Request.Builder requestBuilder = userResponse.request().newBuilder();
if (HttpMethod.permitsRequestBody(method)) {
final boolean maintainBody = HttpMethod.redirectsWithBody(method);
if (HttpMethod.redirectsToGet(method)) {
requestBuilder.method("GET", null);
} else {
RequestBody requestBody = maintainBody ? userResponse.request().body() : null;
requestBuilder.method(method, requestBody);
}
if (!maintainBody) {
requestBuilder.removeHeader("Transfer-Encoding");
requestBuilder.removeHeader("Content-Length");
requestBuilder.removeHeader("Content-Type");
}
}
// way to retain them.
if (!sameConnection(userResponse, url)) {
requestBuilder.removeHeader("Authorization");
}
return requestBuilder.url(url).build();
case HTTP_CLIENT_TIMEOUT:
// repeat the request (even non-idempotent ones.)
if (userResponse.request().body() instanceof UnrepeatableRequestBody) {
return null;
}
return userResponse.request();
default:
return null;
}
}
Aggregations