gpt4 book ai didi

android - retrofit2 okhttp3 android multipart socket tomeout错误

转载 作者:行者123 更新时间:2023-12-03 12:08:49 25 4
gpt4 key购买 nike

我正在尝试使用Retrofit 2上传文件,这给了我
即使添加了超时限制,每次也会出现“socket定时连接超时”错误。对于如何解决这个问题,有任何的建议吗 -

我的Rest客户端设置-

private static void setupRestClient() {
if(LoginToken != null && !LoginToken.isEmpty()) {
OkHttpClient httpClient = new OkHttpClient();
httpClient.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder().addHeader("Authorization", "Bearer "+ LoginToken).build();
return chain.proceed(request);
}
});
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient)
.build();
REST_CLIENT = retrofit.create(Api.class);
} else {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
REST_CLIENT = retrofit.create(Api.class);
}
}

在阅读了关于SO的几个答案之后,我还尝试了-
OkHttpClient httpClient = new OkHttpClient.Builder()
.connectTimeout(12, TimeUnit.MINUTES)
.readTimeout(12, TimeUnit.MINUTES)
.writeTimeout(12, TimeUnit.MINUTES).build();

但是,与此同时也出现了相同的超时错误。
文件上传开始意图-
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(takePictureIntent.resolveActivity(EduwiserMainActivity.this.getPackageManager()) != null){
File photoFile = null;
try{
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCM);
} catch(IOException ex){
Log.e("Error:", "Image file creation failed", ex);
}
if(photoFile != null){
dfCM = "file:" + photoFile.getAbsolutePath();
mCM = photoFile.getPath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if(takePictureIntent != null){
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}

Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Choose image");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, FCR);

意图 Activity 结果-
if(requestCode == FCR && resultCode == -1){
try {
File file = null;
String[] proj = { MediaStore.Images.Media.DATA };
String localPath = mCM != null && !mCM.isEmpty() ? mCM.replace("file:", "") : null;
if(data == null || data.getData() == null){
//Capture Photo if no image available
if(localPath != null){
file = new File(localPath);
}
} else {
String dataString = data.getDataString();
if(dataString != null){
try {
file = new File(PathUtil.getPath(this, Uri.parse(dataString)));
} catch (Exception e){
Log.e("error", e.toString());
}
}
}
final File newFile = file;
defaultPd = new ProgressDialog(EduwiserMainActivity.this);
if(token != null && !token.isEmpty() && newFile != null && documentUploadFileType != null && !documentUploadFileType.isEmpty()){
try {
if(defaultPd != null && !defaultPd.isShowing()) {
defaultPd.show();
defaultPd.setMessage("Uploading file...");
}
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), newFile);
MultipartBody.Part body = MultipartBody.Part.createFormData(!Objects.equals(documentUploadFileType, "profile") ? documentUploadFileType + "_file":
documentUploadFileType, documentUploadFileType + ".jpg", requestFile);
documentUploadFileType = null;
Call<LocalAuthResponse> call = RestClient.get(getApplicationContext()).uploadTeacherDocuments("Bearer " + token, body);
call.enqueue(new Callback<LocalAuthResponse>() {
@Override
public void onResponse(Call<LocalAuthResponse> call, Response<LocalAuthResponse> response) {
try {
if(defaultPd != null && defaultPd.isShowing()) {
defaultPd.dismiss();
}
} catch (Exception e){}
try {
if(response.body() != null && response.body().getSuccess()) {
mWebView.evaluateJavascript("var event = new CustomEvent('refresh_userdata');document.dispatchEvent(event);", null);
}
} catch (Exception e){
// mWebView.evaluateJavascript("var event = new CustomEvent('refresh_userdata');document.dispatchEvent(event);", null);
}
}

@Override
public void onFailure(Call<LocalAuthResponse> call, Throwable t) {
Toast.makeText(getApplicationContext(), "Error Uploading Documents. Please try again.", Toast.LENGTH_LONG).show();
try {
if(defaultPd != null && defaultPd.isShowing()) {
defaultPd.dismiss();
}
} catch (Exception e){}
mWebView.evaluateJavascript("var event = new CustomEvent('fail_attachment');document.dispatchEvent(event);", null);
}
});
} catch (Exception e){
Log.e("error", e.toString());
}
}
} catch(Exception e){
Log.e("error", e.toString());
}
} else if(requestCode == FCR){
mWebView.evaluateJavascript("var event = new CustomEvent('fail_attachment');document.dispatchEvent(event);", null);
}

现在,我在onFailure块中收到“套接字超时错误异常”。
现在,这可能是一个完全不同的错误,该错误引发套接字超时异常,或者这实际上是由于超时引起的。
无论哪种方式,关于如何调试或修复此问题的任何建议?

最佳答案

我假设您正在获取有效的图像文件,所以让我们来上传部分

@Multipart
@POST("api/image/upload")
Call<String> imageUpload(@Part MultipartBody.Part image, @Part("name") RequestBody name);

和上传功能
    private void uploadImage(File file) {
try {
if (file.exists()) {
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("upload", file.getName(), reqFile);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "upload_test");
RestClient.getService().imageUpload(body, name).enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull final Response<String> response) {
newImageUrl = response.body();
}

@Override
public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {

}
});
}
} catch (Exception e) {
toast("Please try again");
}
}

我的改造看起来像这样
new Retrofit.Builder().baseUrl(ConfigHelper.DataServiceUrl)
.addConverterFactory(converterFactory)
.client(client
.addInterceptor(new Interceptor() {
public Response intercept(@NonNull Chain chain) throws IOException {
return chain.proceed(chain.request().newBuilder().addHeader("access_key", finalToken).build());
}
})
.addInterceptor(logging)
.build()).build();

快乐编码:)

关于android - retrofit2 okhttp3 android multipart socket tomeout错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47717526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com