use of com.squareup.okhttp.RequestBody in project Notes by lguipeng.
the class TAndroidTransport method flush.
@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 {
copy(mByteStore.getInputStream(), sink.outputStream());
}
};
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) {
}
}
}
use of com.squareup.okhttp.RequestBody in project rskj by rsksmart.
the class Web3WebSocketServerTest method smokeTest.
private void smokeTest(byte[] msg) throws Exception {
Web3 web3Mock = mock(Web3.class);
String mockResult = "output";
when(web3Mock.web3_sha3(anyString())).thenReturn(mockResult);
int randomPort = 9998;
TestSystemProperties testSystemProperties = new TestSystemProperties();
List<ModuleDescription> filteredModules = Collections.singletonList(new ModuleDescription("web3", "1.0", true, Collections.emptyList(), Collections.emptyList()));
RskWebSocketJsonRpcHandler handler = new RskWebSocketJsonRpcHandler(null);
JsonRpcWeb3ServerHandler serverHandler = new JsonRpcWeb3ServerHandler(web3Mock, filteredModules);
int serverWriteTimeoutSeconds = testSystemProperties.rpcWebSocketServerWriteTimeoutSeconds();
int maxFrameSize = testSystemProperties.rpcWebSocketMaxFrameSize();
int maxAggregatedFrameSize = testSystemProperties.rpcWebSocketMaxAggregatedFrameSize();
assertEquals(DEFAULT_WRITE_TIMEOUT_SECONDS, serverWriteTimeoutSeconds);
assertEquals(DEFAULT_MAX_FRAME_SIZE, maxFrameSize);
assertEquals(DEFAULT_MAX_AGGREGATED_FRAME_SIZE, maxAggregatedFrameSize);
Web3WebSocketServer websocketServer = new Web3WebSocketServer(InetAddress.getLoopbackAddress(), randomPort, handler, serverHandler, serverWriteTimeoutSeconds, maxFrameSize, maxAggregatedFrameSize);
websocketServer.start();
OkHttpClient wsClient = new OkHttpClient();
Request wsRequest = new Request.Builder().url("ws://localhost:" + randomPort + "/websocket").build();
WebSocketCall wsCall = WebSocketCall.create(wsClient, wsRequest);
CountDownLatch wsAsyncResultLatch = new CountDownLatch(1);
CountDownLatch wsAsyncCloseLatch = new CountDownLatch(1);
AtomicReference<Exception> failureReference = new AtomicReference<>();
wsCall.enqueue(new WebSocketListener() {
private WebSocket webSocket;
@Override
public void onOpen(WebSocket webSocket, Response response) {
wsExecutor.submit(() -> {
RequestBody body = RequestBody.create(WebSocket.TEXT, msg);
try {
this.webSocket = webSocket;
this.webSocket.sendMessage(body);
this.webSocket.close(1000, null);
} catch (IOException e) {
failureReference.set(e);
}
});
}
@Override
public void onFailure(IOException e, Response response) {
failureReference.set(e);
}
@Override
public void onMessage(ResponseBody message) throws IOException {
JsonNode jsonRpcResponse = OBJECT_MAPPER.readTree(message.bytes());
assertThat(jsonRpcResponse.at("/result").asText(), is(mockResult));
message.close();
wsAsyncResultLatch.countDown();
}
@Override
public void onPong(Buffer payload) {
}
@Override
public void onClose(int code, String reason) {
wsAsyncCloseLatch.countDown();
}
});
if (!wsAsyncResultLatch.await(10, TimeUnit.SECONDS)) {
fail("Result timed out");
}
if (!wsAsyncCloseLatch.await(10, TimeUnit.SECONDS)) {
fail("Close timed out");
}
websocketServer.stop();
Exception failure = failureReference.get();
if (failure != null) {
failure.printStackTrace();
fail(failure.getMessage());
}
}
use of com.squareup.okhttp.RequestBody in project AisenWeiBo by wangdan.
the class DefHttpUtility method doPostFiles.
@Override
public <T> T doPostFiles(HttpConfig config, Setting action, Params urlParams, Params bodyParams, MultipartFile[] files, Class<T> responseCls) throws TaskException {
String method = "doPostFiles";
Request.Builder builder = createRequestBuilder(config, action, urlParams, method);
MultipartBuilder multipartBuilder = new MultipartBuilder();
multipartBuilder.type(MultipartBuilder.FORM);
// 处理Body参数
if (bodyParams != null && bodyParams.getKeys().size() > 0) {
for (String key : bodyParams.getKeys()) {
String value = bodyParams.getParameter(key);
multipartBuilder.addFormDataPart(key, value);
Logger.d(getTag(action, method), "BodyParam[%s, %s]", key, value);
}
}
// 处理文件数据
if (files != null && files.length > 0) {
for (MultipartFile file : files) {
// 普通字节流
if (file.getBytes() != null) {
multipartBuilder.addFormDataPart(file.getKey(), file.getKey(), createRequestBody(file));
Logger.d(getTag(action, method), "Multipart bytes, length = " + file.getBytes().length);
} else // 文件
if (file.getFile() != null) {
multipartBuilder.addFormDataPart(file.getKey(), file.getFile().getName(), createRequestBody(file));
Logger.d(getTag(action, method), "Multipart file, name = %s, path = %s", file.getFile().getName(), file.getFile().getAbsolutePath());
}
}
}
RequestBody requestBody = multipartBuilder.build();
builder.post(requestBody);
return executeRequest(builder.build(), responseCls, action, method);
}
use of com.squareup.okhttp.RequestBody in project pictureapp by EyeSeeTea.
the class PushClient method pushData.
/**
* Pushes data to DHIS Server
*/
private JSONObject pushData(JSONObject data) throws ApiCallException {
Response response = null;
final String DHIS_URL = getDhisURL();
OkHttpClient client = UnsafeOkHttpsClientFactory.getUnsafeOkHttpClient();
// connect timeout
client.setConnectTimeout(30, TimeUnit.SECONDS);
// socket timeout
client.setReadTimeout(30, TimeUnit.SECONDS);
// write timeout
client.setWriteTimeout(30, TimeUnit.SECONDS);
// Cancel retry on failure
client.setRetryOnConnectionFailure(false);
BasicAuthenticator basicAuthenticator = new BasicAuthenticator();
client.setAuthenticator(basicAuthenticator);
RequestBody body = RequestBody.create(JSON, data.toString());
Request request = new Request.Builder().header(basicAuthenticator.AUTHORIZATION_HEADER, basicAuthenticator.getCredentials()).url(DHIS_URL).post(body).build();
try {
response = client.newCall(request).execute();
} catch (IOException e) {
throw new ApiCallException(e);
}
return ServerApiUtils.getApiResponseAsJSONObject(response);
}
use of com.squareup.okhttp.RequestBody in project pictureapp by EyeSeeTea.
the class BasicAuthenticator method executeCall.
/**
* Call to DHIS Server
*/
static Response executeCall(JSONObject data, String url, String method) throws ApiCallException {
final String DHIS_URL = url;
Log.d(method, DHIS_URL);
OkHttpClient client = UnsafeOkHttpsClientFactory.getUnsafeOkHttpClient();
BasicAuthenticator basicAuthenticator = new BasicAuthenticator();
client.setAuthenticator(basicAuthenticator);
Request.Builder builder = new Request.Builder().header(basicAuthenticator.AUTHORIZATION_HEADER, basicAuthenticator.getCredentials()).url(DHIS_URL);
switch(method) {
case "POST":
RequestBody postBody = RequestBody.create(JSON, data.toString());
builder.post(postBody);
break;
case "PUT":
RequestBody putBody = RequestBody.create(JSON, data.toString());
builder.put(putBody);
break;
case "PATCH":
RequestBody patchBody = RequestBody.create(JSON, data.toString());
builder.patch(patchBody);
break;
case "GET":
builder.get();
break;
}
Request request = builder.build();
Response response = null;
try {
response = client.newCall(request).execute();
} catch (IOException ex) {
throw new ApiCallException(ex);
}
return response;
}
Aggregations