use of okhttp3.MediaType in project WeexErosFramework by bmfe.
the class AxiosManager method createRequestBodyByMediaType.
private RequestBody createRequestBodyByMediaType(Map<String, String> header, String content) {
if (header != null && !TextUtils.isEmpty(header.get("Content-Type"))) {
String s = header.get("Content-Type");
MediaType mediaType = null;
try {
mediaType = MediaType.parse(s);
} catch (Exception e) {
e.printStackTrace();
}
if (mediaType == null) {
mediaType = MediaType.parse(DEFAULT_MEDIATYPE);
}
return RequestBody.create(mediaType, content);
}
return RequestBody.create(MediaType.parse(DEFAULT_MEDIATYPE), content);
}
use of okhttp3.MediaType in project couchbase-lite-android by couchbase.
the class ReplicatorWithSyncGatewayDBTest method sendRequestToEndpoint.
JSONObject sendRequestToEndpoint(URLEndpoint endpoint, String method, String path, String mediaType, byte[] body) throws Exception {
URI endpointURI = endpoint.getURL();
String _scheme = endpointURI.getScheme().equals(URLEndpoint.kURLEndpointTLSScheme) ? "https" : "http";
String _host = endpointURI.getHost();
int _port = endpointURI.getPort() + 1;
path = (path != null) ? (path.startsWith("/") ? path : "/" + path) : "";
String _path = String.format(Locale.ENGLISH, "%s%s", endpointURI.getPath(), path);
URI uri = new URI(_scheme, null, _host, _port, _path, null, null);
OkHttpClient client = new OkHttpClient();
okhttp3.Request.Builder builder = new okhttp3.Request.Builder().url(uri.toURL());
RequestBody requestBody = null;
if (body != null && body instanceof byte[])
requestBody = RequestBody.create(MediaType.parse(mediaType), body);
builder.method(method, requestBody);
okhttp3.Request request = builder.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
Log.i(TAG, "Send request succeeded; URL=<%s>, Method=<%s>, Status=%d", uri, method, response.code());
return new JSONObject(response.body().string());
} else {
// error
Log.e(TAG, "Failed to send request; URL=<%s>, Method=<%s>, Status=%d, Error=%s", uri, method, response.code(), response.message());
return null;
}
}
use of okhttp3.MediaType in project couchbase-lite-android by couchbase.
the class ReplicatorWithSyncGatewayTest method getSessionAuthenticatorFromSG.
SessionAuthenticator getSessionAuthenticatorFromSG() throws Exception {
// Obtain Sync-Gateway Session ID
final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String url = String.format(Locale.ENGLISH, "http://%s:4985/seekrit/_session", config.remoteHost());
RequestBody body = RequestBody.create(JSON, "{\"name\": \"pupshaw\"}");
Request request = new Request.Builder().url(url).post(body).build();
Response response = client.newCall(request).execute();
String respBody = response.body().string();
Log.e(TAG, "json string -> " + respBody);
JSONObject json = new JSONObject(respBody);
return new SessionAuthenticator(json.getString("session_id"), json.getString("cookie_name"));
}
use of okhttp3.MediaType in project ignite by apache.
the class RestExecutor method sendRequest0.
/**
*/
private RestResult sendRequest0(String nodeUrl, boolean demo, String path, Map<String, Object> params, Map<String, Object> headers, String body) throws IOException {
if (demo && AgentClusterDemo.getDemoUrl() == null) {
try {
AgentClusterDemo.tryStart().await();
} catch (InterruptedException ignore) {
throw new IllegalStateException("Failed to send request because of embedded node for demo mode is not started yet.");
}
}
String url = demo ? AgentClusterDemo.getDemoUrl() : nodeUrl;
HttpUrl httpUrl = HttpUrl.parse(url);
if (httpUrl == null)
throw new IllegalStateException("Failed to send request because of node URL is invalid: " + url);
HttpUrl.Builder urlBuilder = httpUrl.newBuilder();
if (path != null)
urlBuilder.addPathSegment(path);
final Request.Builder reqBuilder = new Request.Builder();
if (headers != null) {
for (Map.Entry<String, Object> entry : headers.entrySet()) if (entry.getValue() != null)
reqBuilder.addHeader(entry.getKey(), entry.getValue().toString());
}
if (body != null) {
MediaType contentType = MediaType.parse("text/plain");
reqBuilder.post(RequestBody.create(contentType, body));
} else {
FormBody.Builder formBody = new FormBody.Builder();
if (params != null) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
if (entry.getValue() != null)
formBody.add(entry.getKey(), entry.getValue().toString());
}
}
reqBuilder.post(formBody.build());
}
reqBuilder.url(urlBuilder.build());
try (Response resp = httpClient.newCall(reqBuilder.build()).execute()) {
if (resp.isSuccessful()) {
RestResponseHolder res = MAPPER.readValue(resp.body().byteStream(), RestResponseHolder.class);
int status = res.getSuccessStatus();
switch(status) {
case STATUS_SUCCESS:
return RestResult.success(res.getResponse());
default:
return RestResult.fail(status, res.getError());
}
}
if (resp.code() == 401)
return RestResult.fail(STATUS_AUTH_FAILED, "Failed to authenticate in cluster. " + "Please check agent\'s login and password or node port.");
if (resp.code() == 404)
return RestResult.fail(STATUS_FAILED, "Failed connect to cluster.");
return RestResult.fail(STATUS_FAILED, "Failed to execute REST command: " + resp.message());
}
}
use of okhttp3.MediaType in project YhLibraryForAndroid by android-coco.
the class OkHttpRequestManager method postString.
@Override
public void postString(final String host, final String suffix, Map<String, String> headers, final String params, final HttpCallBack callback, final Object tag, final long connTimeOut, final long readTimeOut, final long writeTimeOut) {
final String url = host + suffix;
// 组成的URL 为空或者不是http或https开头都是非法URL
if (isEmpty(url) || (!url.startsWith(Constants.FILE_HTTP) && !url.startsWith(Constants.FILE_HTTPS))) {
callback.onFailure(-3, "非法URL");
callback.onFinish();
return;
}
if (StringUtils.isEmpty(headers)) {
headers = this.headers;
}
OkHttpUtils.postString().url(url).headers(headers).tag(tag).content(params).mediaType(MediaType.parse("application/json; charset=utf-8")).build().connTimeOut(connTimeOut).readTimeOut(readTimeOut).writeTimeOut(writeTimeOut).execute(new StringCallback() {
@Override
public void onResponse(String response, int id) {
try {
JSONObject json = new JSONObject(response);
String ret = json.getString(Constants.RESULT);
if (ERROE_3001.equals(ret) || ERROE_3002.equals(ret)) {
// 相关操作
// EventBus.getDefault().post(
// new EventBusBean(new Intent(
// AppConfig.ACTION_PLOGIN_OUT)));
// EventBus.getDefault().post(
// new EventBusBean(new Intent(
// AppConfig.ACTION_AGAIN_TOKEN)));
} else {
callback.onSuccess(response);
callback.onFinish();
}
} catch (JSONException e) {
callback.onSuccess(response);
callback.onFinish();
}
}
@Override
public void onError(Call call, Exception e, int id) {
// + e + " " + id);
if (!isEmpty(e)) {
if (e instanceof java.net.SocketTimeoutException) {
callback.onFailure(-5, "请求超时");
callback.onFinish();
} else if (e instanceof java.net.ConnectException) {
callback.onFailure(-4, "连接超时");
callback.onFinish();
} else {
dealError(e, callback);
}
}
}
});
}
Aggregations