MainActivity.csXamarin Android請求服務器不是建立而是獲得異常?
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
Button button = FindViewById<Button>(Resource.Id.Browse);
button.Click += BrowseButtonOnClick;
}
void BrowseButtonOnClick(object sender, EventArgs eventArs)
{
Intent = new Intent();
Intent.SetType("image/*");
Intent data = Intent.SetAction(Intent.ActionGetContent);
try
{
StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"), PickImageId);
}
catch (ActivityNotFoundException ex)
{
Toast.MakeText(this, "Please install a File Manager.", ToastLength.Long).Show();
}
catch (Exception ex)
{
Toast.MakeText(this, "Error occured ", ToastLength.Long).Show();
}
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if ((requestCode == PickImageId) && (resultCode == Result.Ok) && (data != null))
{
UploadFile(data);
}
}
void UploadFile(Intent data)
{
ICursor cursor = null;
try
{
Button upButton = FindViewById<Button>(Resource.Id.Upload);
// assuming image
var docID = DocumentsContract.GetDocumentId(data.Data);
var id = docID.Split(':')[1];
var whereSelect = MediaStore.Images.ImageColumns.Id + "=?";
var projections = new string[] { MediaStore.Images.ImageColumns.Data };
// Try internal storage first
cursor = ContentResolver.Query(MediaStore.Images.Media.InternalContentUri, projections, whereSelect, new string[] { id }, null);
if (cursor.Count == 0)
{
// not found on internal storage, try external storage
cursor = ContentResolver.Query(MediaStore.Images.Media.ExternalContentUri, projections, whereSelect, new string[] { id }, null);
}
var colData = cursor.GetColumnIndexOrThrow(MediaStore.Images.ImageColumns.Data);
cursor.MoveToFirst();
var fullPathToImage = cursor.GetString(colData);
string fpti = cursor.GetString(colData);
//Toast.MakeText(this, fullPathToImage, ToastLength.Long).Show();
// Log.Info("MediaPath", fullPathToImage);
//var client = new HttpClient();
//Android.Net.Uri uri = data.Data;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileInputStream fis = new FileInputStream(new File(fullPathToImage)); //uri.Path
byte[] buf = new byte[1024];
int n;
while (-1 != (n = fis.Read(buf)))
baos.Write(buf, 0, n);
byte[] vBytes = baos.ToByteArray();
ByteArrayContent byteContent = new ByteArrayContent(vBytes);
//var UploadServiceBaseAddress = "http://192.168.3.157:81/Values/UploadFile?file=";
//StringContent stringContent = new StringContent(UploadServiceBaseAddress, System.Text.Encoding.UTF8);
string base64 = Convert.ToBase64String(vBytes);
string strb64 = Convert.ToString(base64);
upButton.Click += (sender, args) =>
{
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.SetTitle("Please wait...");
progressDialog.SetCancelable(false);
Task.Run(async() =>
{
try
{
RunOnUiThread(() =>
{
progressDialog.Show();
});
string dataUsed = await SendReceiveTest.Test(strb64);
string me = "Uploading...";
Toast.MakeText(this, me, ToastLength.Long).Show();
RunOnUiThread(() =>
{
progressDialog.Dismiss();
});
string msg = "Upload Completed";
Toast.MakeText(this, msg, ToastLength.Long).Show();
Toast.MakeText(this, dataUsed, ToastLength.Long).Show();
}
catch (Exception ex)
{
Log.Error("MediaPath", ex.Message);
}
});
};
}
catch (Exception ex)
{
Log.Error("MediaPath", ex.Message);
}
finally
{
cursor?.Close();
cursor?.Dispose();
}
}
}
}
SendReceiveTest.cs
public static async Task<string> Test(string data)
{
try
{
using (var client = new HttpClient())
{
var uri = $"http://192.168.3.157:81/Values/UploadFile?file={data}";
var response = await client.GetAsync(uri);
var stringData = await response.Content.ReadAsStringAsync();
//Context c = null;
//Toast.MakeText(c, stringData, ToastLength.Long).Show();
return stringData;
}
}
catch (Exception ex)
{
Log.Error("MediaPath", ex.Message);
}
return null;
在異常前
{System.Net.Http.HttpRequestException: An error occurred while sending the request ---> System.Net.WebException: Error getting response stream (ReadDone2): ReceiveFailure ---> System.Exception: at System.Net.WebConnection.HandleError (System.Net.WebExceptionStatus st, System.Exception e, System.String where) [0x00000] in <a547bd0d78184f26ab08d022f013c1e1>:0
at System.Net.WebConnection.ReadDone (System.IAsyncResult result) [0x00000] in <a547bd0d78184f26ab08d022f013c1e1>:0
at System.Net.Sockets.SocketAsyncResult+<>c__DisplayClass27_0.<Complete>b__0 (System.Object _) [0x00000] in <a547bd0d78184f26ab08d022f013c1e1>:0
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
at System.Threading.ThreadPoolWorkQueue.Dispatch() [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback() [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
at System.Net.WebConnection.HandleError (System.Net.WebExceptionStatus st, System.Exception e, System.String where) [0x0003b] in <a547bd0d78184f26ab08d022f013c1e1>:0
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.EndGetResponse (System.IAsyncResult asyncResult) [0x00058] in <a547bd0d78184f26ab08d022f013c1e1>:0
at System.Threading.Tasks.TaskFactory`1[TResult].FromAsyncCoreLogic (System.IAsyncResult iar, System.Func`2[T,TResult] endFunction, System.Action`1[T] endAction, System.Threading.Tasks.Task`1[TResult] promise, System.Boolean requiresSynchronization) [0x0000f] in <3fd174ff54b146228c505f23cf75ce71>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <3fd174ff54b146228c505f23cf75ce71>:0
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[TResult].GetResult() [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
at System.Net.Http.HttpClientHandler+<SendAsync>d__63.MoveNext() [0x003e6] in <b696532a7c264e5e866cb15a1b40a4a4>:0
--- End of inner exception stack trace ---
at System.Net.Http.HttpClientHandler+<SendAsync>d__63.MoveNext() [0x00449] in <b696532a7c264e5e866cb15a1b40a4a4>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <3fd174ff54b146228c505f23cf75ce71>:0
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[TResult].GetResult() [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
at System.Net.Http.HttpClient+<SendAsyncWorker>d__49.MoveNext() [0x000ca] in <b696532a7c264e5e866cb15a1b40a4a4>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <3fd174ff54b146228c505f23cf75ce71>:0
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0
at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult() [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
at XAFileUpload.SendReceiveTest+<Test>d__0.MoveNext() [0x00066] in C:\Users\sandeepsubbiahs\Documents\Visual Studio 2017\Projects\Xamarin\XAFileUpload\XAFileUpload\SendReceiveTest.cs:28 }
在Ex.Message
"An error occurred while sending the request"
在內部異常
內部狀態:System.Net.WebExceptionInternalStatus.RequestFatal
狀態:System.Net.WebExceptionStatus。 ReceiveFailure
我有一個2按鈕(瀏覽,上傳),通過點擊第一個按鈕瀏覽它將搭載由Xamarin Android模擬器的圖片,然後單擊第二個按鈕上傳它發送的圖片作爲base64string到服務器通過使用SendReceiveTest後類和它的方法測試()但發送請求到服務器時發生異常,並在上面提到。
剛剛發現爲什麼我得到這個異常它的bcoz ** Base64String **太長,所以我如何解決它? – Sandeep
拿了一個低分辨率的圖片現在解決了我的問題。 – Sandeep