我正在开发一款Windows Phone 8应用程序。现在我必须将从我的画廊中选择的图像发布到web api。这个api受密码保护,因此需要传递http客户端库的身份验证头中的用户名和密码。其次,图像,aboutme和其他属性形式的数据将在api上发布。但是有一个问题我不知道它的崩溃程度。我已经在这个代码片段中给出了文本api,如果实际需要那么你可以问我。但需要知道我在使用表单数据传递http客户端标题时出错了。 我的代码片段如下:
async void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
// MessageBox.Show(e.ChosenPhoto.Length.ToString());
//Code to display the photo on the page in an image control named myImage.
photoStream = new MemoryStream();
e.ChosenPhoto.CopyTo(photoStream);
fileName = e.OriginalFileName;
MessageBox.Show(fileName);
System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
int a = bmp.PixelHeight;
int b = bmp.PixelWidth;
ApplicationSettingHelper.AddOrUpdateValue("profilepicture", e.OriginalFileName);
ApplicationSettingHelper.Save();
string User_id = "221296";
string About_me = AboutMeText.Text;
string Country = "Dubai";
string Session_token = "54143870560e6136764dc9.77573702";
byte[] Imagedata = bitmapConverter(bmp);
UploadFile(User_id, About_me, Country, Session_token, photoStream);
}
/////////////////////////////////////////////// /////////
private async void UploadFile(string user_id,string about_me,string country,string session_token,MemoryStream photoStream)
{
try
{
// Make sure there is a picture selected
if (photoStream != null)
{
const string uri = "http://api.etc";
using (var client = new HttpClient())
{
var byteArray = Encoding.UTF8.GetBytes("prototype:prototype");
var header = new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(byteArray));
client.DefaultRequestHeaders.Authorization = header;
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StreamContent(photoStream), "profile_image");
content.Add(new StringContent(user_id), "user_id");
content.Add(new StringContent(about_me), "about_me");
content.Add(new StringContent(country), "country");
content.Add(new StringContent(session_token), "session_token");
// var result = await client.PostAsync(uri, content);
await client.PostAsync(uri, content)
.ContinueWith((postTask) =>
{
postTask.Result.EnsureSuccessStatusCode();
});
}
}
catch(Exception ex)
{
var message = ex.Message + ex.StackTrace.ToString();
var test = message;
}
}