use of com.squareup.okhttp.Request in project NewXmPluginSDK by MiEcosystem.
the class TestCaseActivity method uploadFile.
public Response uploadFile(String url, String filePath) throws IOException {
Log.d("test", "url:" + url);
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(30, TimeUnit.SECONDS);
client.setReadTimeout(15, TimeUnit.SECONDS);
client.setWriteTimeout(30, TimeUnit.SECONDS);
Request request = new Request.Builder().url(url).put(RequestBody.create(MediaType.parse(""), new File(filePath))).build();
return client.newCall(request).execute();
}
use of com.squareup.okhttp.Request 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.Request in project Android-Universal-Image-Loader by nostra13.
the class OkHttpImageDownloader method getStreamFromNetwork.
@Override
protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
Request request = new Request.Builder().url(imageUri).build();
ResponseBody responseBody = client.newCall(request).execute().body();
InputStream inputStream = responseBody.byteStream();
int contentLength = (int) responseBody.contentLength();
return new ContentLengthInputStream(inputStream, contentLength);
}
use of com.squareup.okhttp.Request in project grpc-java by grpc.
the class OkHttpClientTransport method createHttpProxySocket.
private Socket createHttpProxySocket(InetSocketAddress address, InetSocketAddress proxyAddress, String proxyUsername, String proxyPassword) throws StatusException {
try {
Socket sock;
// The proxy address may not be resolved
if (proxyAddress.getAddress() != null) {
sock = socketFactory.createSocket(proxyAddress.getAddress(), proxyAddress.getPort());
} else {
sock = socketFactory.createSocket(proxyAddress.getHostName(), proxyAddress.getPort());
}
sock.setTcpNoDelay(true);
Source source = Okio.source(sock);
BufferedSink sink = Okio.buffer(Okio.sink(sock));
// Prepare headers and request method line
Request proxyRequest = createHttpProxyRequest(address, proxyUsername, proxyPassword);
HttpUrl url = proxyRequest.httpUrl();
String requestLine = String.format("CONNECT %s:%d HTTP/1.1", url.host(), url.port());
// Write request to socket
sink.writeUtf8(requestLine).writeUtf8("\r\n");
for (int i = 0, size = proxyRequest.headers().size(); i < size; i++) {
sink.writeUtf8(proxyRequest.headers().name(i)).writeUtf8(": ").writeUtf8(proxyRequest.headers().value(i)).writeUtf8("\r\n");
}
sink.writeUtf8("\r\n");
// Flush buffer (flushes socket and sends request)
sink.flush();
// Read status line, check if 2xx was returned
StatusLine statusLine = StatusLine.parse(readUtf8LineStrictUnbuffered(source));
// Drain rest of headers
while (!readUtf8LineStrictUnbuffered(source).equals("")) {
}
if (statusLine.code < 200 || statusLine.code >= 300) {
Buffer body = new Buffer();
try {
sock.shutdownOutput();
source.read(body, 1024);
} catch (IOException ex) {
body.writeUtf8("Unable to read body: " + ex.toString());
}
try {
sock.close();
} catch (IOException ignored) {
// ignored
}
String message = String.format("Response returned from proxy was not successful (expected 2xx, got %d %s). " + "Response body:\n%s", statusLine.code, statusLine.message, body.readUtf8());
throw Status.UNAVAILABLE.withDescription(message).asException();
}
return sock;
} catch (IOException e) {
throw Status.UNAVAILABLE.withDescription("Failed trying to connect with proxy").withCause(e).asException();
}
}
use of com.squareup.okhttp.Request in project AisenWeiBo by wangdan.
the class PictureSizeHttpUtility method doGet.
@Override
public <T> T doGet(HttpConfig config, Setting action, Params urlParams, Class<T> responseCls) throws TaskException {
if (GlobalContext.getInstance() == null || SystemUtils.getNetworkType(GlobalContext.getInstance()) == SystemUtils.NetWorkType.none)
return null;
String url = urlParams.getParameter("path");
PictureSize size = new PictureSize();
size.setUrl(url);
Request request = new Request.Builder().url(url).build();
try {
Response response = GlobalContext.getOkHttpClient().newCall(request).execute();
if (!(response.code() == HttpURLConnection.HTTP_OK || response.code() == HttpURLConnection.HTTP_PARTIAL)) {
throw new TaskException(String.valueOf(TaskException.TaskError.failIOError));
} else {
// 图片大小
String header = response.header("Content-Length");
int length = Integer.parseInt(header);
size.setSize(length);
SinaDB.getDB().insert(null, size);
Logger.d(TAG, String.format("图片大小 %s", String.valueOf(size.getSize())));
}
} catch (Exception e) {
throw new TaskException(String.valueOf(TaskException.TaskError.failIOError));
}
return (T) size;
}
Aggregations