Response{protocol=http/1.1, code=504, message=GATEWAY_TIMEOUT, url=https://************************}
I am getting
code=504, message=GATEWAY_TIMEOUT
in android but the same url got success in iOS
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(30*1000, TimeUnit.MILLISECONDS)
.readTimeout(30*1000, TimeUnit.MILLISECONDS)
.writeTimeout(30*1000, TimeUnit.MILLISECONDS)
.retryOnConnectionFailure(false)
.build();
Request request = new Request.Builder().url(urlStr).post(formBody)
.addHeader("Authorization", g.getTokenType() + " " + g.getAccessToken())
.addHeader("Content-type", "application/x-www-form-urlencoded")
try {
Response mResponse = client.newCall(request).execute();
String jsonString = mResponse.body().string();
Try This
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(30*1000, TimeUnit.SECONDS)
.readTimeout(30*1000, TimeUnit.SECONDS)
.writeTimeout(30*1000, TimeUnit.SECONDS)
.retryOnConnectionFailure(false)
.build();
Put the timeout in minutes as per your server speed time requirement.
Try this :-
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.readTimeout(2, TimeUnit.MINUTES);
httpClient.connectTimeout(2, TimeUnit.MINUTES);
httpClient.writeTimeout(2, TimeUnit.MINUTES);
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request.Builder builder = original.newBuilder();
builder.method(original.method(), original.body());
builder.header("Accept", "application/json");
if (TOKEN.length() > 0)
builder.header("Authorization", TOKEN);
return chain.proceed(builder.build());
}
});
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(interceptor);
OkHttpClient client = httpClient.build();
Gson gson = new GsonBuilder()
.setLenient()
.create();
Related
I'm currently studying retrofit in android:
and this is my current code:
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder()
.addHeader("Authorization", "Bearer " + Globals.BEARER_TOKEN)
.build();
return chain.proceed(newRequest);
}
}).build();
How can i add my HttpLoggingInterceptor to the client and also at the same time add my header to the client?
You can add both interceptors calling the method addInterceptor twice:
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder()
.addHeader("Authorization", "Bearer " + Globals.BEARER_TOKEN)
.build();
return chain.proceed(newRequest);
}
})
.addInterceptor(interceptor).build();
To add an interceptor to Retrofit you include it while building OkHttpClient,
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new HttpLoggingInterceptor())
Then you build Retrofit using this client,
Retrofit.Builder builder = new Retrofit.Builder()
.client(client);
Retrofit retrofit = builder.build();
On some device i have no problems with a communication with the server used with the retrofit framework. I also used several Android versions to verify that the code run. But on some devices (Samsung S8) I got each time an error: 'Handshake failed'. Does anybody have an idea where is the problem? Thanks!
Here is my code:
protected static Retrofit getInstanceWithoutToken() {
final OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
final Request original = chain.request();
final Request request = original.newBuilder()
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
});
return new Retrofit.Builder()
.baseUrl(CommonConstantsRest.REST_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
}
The problem was the ssl communication. Adding the following CipherSuite solved the problem
protected static Retrofit getInstanceWithoutToken() {
ConnectionSpec spec = new
ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2)
.cipherSuites(
CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256)
.build();
final OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
httpClient.connectionSpecs(Collections.singletonList(spec));
httpClient
.addInterceptor(logging)
.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
final Request original = chain.request();
final Request request = original.newBuilder()
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
});
return new Retrofit.Builder()
.baseUrl(CommonConstantsRest.REST_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
}
I using OkhttpClient to send a video with 15 seconds long to the server using OkhttpClient 3.2 and Retrofit2,sometimes it work fine but sometimes I get the error below,which is very inconsistent.
java.net.SocketTimeoutException: timeout
Here is my code for sending the video up to server
private void sendVideoToServer( final String videoFilePath,final String api_key)
{
File videoFile = new File(videoFilePath);
RequestBody videoBody = RequestBody.create(MediaType.parse("video/*"), videoFile);
MultipartBody.Part vFile = MultipartBody.Part.createFormData("video", videoFile.getName(), videoBody);
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
okhttp3.Request.Builder ongoing = chain.request().newBuilder();
ongoing.addHeader("authorization", api_key);
return chain.proceed(ongoing.build());
}
})
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(AppConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient)
.build();
VideoInterface videoInterface = retrofit.create(VideoInterface.class);
Call<ResultObject> serverCom = videoInterface.sendVideoToServer(vFile);
serverCom.enqueue(new Callback<ResultObject>() {
#Override
public void onResponse(Call<ResultObject> call, retrofit2.Response<ResultObject> response) {
ResultObject result = response.body();
if(!TextUtils.isEmpty(result.getSuccess())){
Log.d("video Result " , result.getSuccess());
}
}
#Override
public void onFailure(Call<ResultObject> call, Throwable t) {
Log.d("video error",t.toString());
}
});
}
After reading some question,I tried to set the connection timeout to the OkhttpClient like below,but still cant solve the problem.
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
okhttp3.Request.Builder ongoing = chain.request().newBuilder();
ongoing.addHeader("authorization", api_key);
return chain.proceed(ongoing.build());
}
});
builder.connectTimeout(5, TimeUnit.MINUTES)
.writeTimeout(5, TimeUnit.MINUTES)
.readTimeout(5, TimeUnit.MINUTES);
OkHttpClient httpClient = builder.build();
I totally dont know what was doing wrong in this part,somebody please give me some guidance. Tq
try passing actual file object
file = new File(tasks.getImageUrl());
requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
sendVideo(body);
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
okhttp3.Request.Builder ongoing = chain.request().newBuilder();
ongoing.addHeader("authorization", api_key);
return chain.proceed(ongoing.build());
}
})
// Add below line to your okhttp client
.connectTimeout(60, TimeUnit.SECONDS)
.build();
i using retrofit2 and want add some header using OkHttp3 addInterceptor
but not working
this is my code
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.removeHeader("Authorization")
.removeHeader("Content-type")
.removeHeader("User-Agent")
.addHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8")
.addHeader("Accept-Language", "en-US")
.addHeader("User-Agent", ApiConfig.userAgent)
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
});
OkHttpClient client = httpClient.build();
if (apiInterface == null) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiConfig.baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(client)
.build();
apiInterface = retrofit.create(ApiInterface.class);
}
return apiInterface;
please help me.
kind regards
Try this if it helps
RestAdapter.Builder builder = new RestAdapter.Builder()
.setRequestInterceptor(new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
request.addHeader("Accept", "application/json;versions=1");
if (isUserLoggedIn()) {
request.addHeader("Authorization", getToken());
}
}
});
I have used this method https://stackoverflow.com/a/31744565/5829906 but doesnt post data.
Here is my code
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addFormDataPart("rating", "5").addFormDataPart("comment", "Awesome")
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
String responseString = response.body().string();
response.body().close();
}catch (Exception e) {
e.printStackTrace();
}
I tried DefaultHttpClient , that seems to be working, but it shows deprecated, so thought of trying something different..Cant figure out what is wrong in this
You select MediaType MultipartBuilder.FORM
which is for uploading the file/image as multipart
public static final MediaType FORM = MediaType.parse("multipart/form-data");
try to send like this as
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
RequestBody formBody = new FormBody.Builder().add("search", "Jurassic Park").build();
Request request = new Request.Builder().url("https://en.wikipedia.org/w/index.php").post(formBody).build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful())
throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
For those that may still come here, using with Retrofi2 and passing your data correctly to the request body. Even if you set "application/x-www-form-urlencoded" and you did not pass your data properly, you will still have issue. That was my situstion
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.addHeader("ContentType", "application/x-www-form-urlencoded");
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
OkHttpClient client = httpClient.build();
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
Api api = retrofit.create(Api.class);
Then make sure you pass your data to your api endpoint as shown below. NOT as JSON, or class object or string but as request body.
RequestBody formBody = new FormBody.Builder()
.addEncoded("grant_type", "password")
.addEncoded("username", username)
.addEncoded("password", password)
.build();
call your api service
Call<Response> call = api.login(formBody);
I hope this helps somebody