通过HttpClient进行HTTPS调用获取404 - 未找到

时间:2014-02-03 00:16:34

标签: c# windows windows-phone-8 windows-phone

我一直在为这个特殊问题疯狂。我要做的是在用户单击注册按钮后对服务器进行HTTPS调用。服务器必须将新用户添加到数据库并向我发回用户密钥。我已经使用没有HTTPS的本地LAMP服务器测试了httpClient类。工作良好。当我尝试使用SSL连接到制作服务器时,我获得了404 - 未找到。我仔细检查了URL,内容和授权格式是否正确。作为一个问题,我将其编码在控制台应用程序中,并且每次都连接到生产服务器。它只适用于Windows手机模拟器或我的Windows手机。用提琴手监视一切。我也使用WebClient类无济于事。请帮助!

以下代码!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JailBird_ProtoType.Models
{
   // CLASS USED TO FORMAT OBJECT TO JSON STRING
    public class TestUser
    {
        public string Name { set; get; }
        public string Email { get; set; }
        public string Password { set; get; }
        public List<string> Roles = new List<string>();
    }
}

using Microsoft.Phone.Net.NetworkInformation;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace JailBird_ProtoType.Services
{
    public class UploadJsonService
    {
        private BackgroundWorker bw = new BackgroundWorker();
        public BackgroundWorker GetBackGroundWorker { get { return bw; } }

        private HttpClient client = new HttpClient();
        private HttpClient GetClient { get { return client; } }

        private HttpResponseMessage response;
        public HttpResponseMessage GetResponseMessage { get { return response; } }

        // SET THE UPLOAD URL
        private string uploadURL;
        public string SetUploadURL { set { uploadURL = value; } }

        // SET THE STRING DATA UPLOAD VALUE
        private string jsonValue ="";
        public string SetJsonValue { set { jsonValue = value; } }

        private HttpContent httpContent;
        public HttpContent GetHttpContent { get { return httpContent; } set { httpContent = value; } }

        // SET THE METHOD TYPE UPLOAD VALUE
        private string Method = "POST";
        public string SetMethod { set { Method = value; } }


        // CONSRUCTOR
       public UploadJsonService()
        {
            SetUpClass();
        }

        public UploadJsonService(string url, string data)
        {
            SetUploadURL = url;
            SetJsonValue = data;
            SetUpClass();
        }

        public UploadJsonService(string url, string method, string data)
        {
            SetUploadURL = url;
            SetJsonValue = data;
            SetMethod = method;
            SetUpClass();
        }


        private void SetUpClass()
        {
            bw.DoWork += new DoWorkEventHandler(DoWork);

            httpContent = new StringContent(jsonValue);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        }


        public void StartUpload()
        {
            try
            {
                bw.RunWorkerAsync(); // RUN BACKGROUND WORKER
            }
            catch (Exception) { }
        }

        public void CancelUpload()
        {
            // CANCEL ALL WORKER TASKS
            try
            {
                client.Dispose();
                httpContent = null;
                bw.CancelAsync();
            }
            catch (Exception) { }
        }

        public void SetHeader(string header, string value)
        {
            client.DefaultRequestHeaders.Add(header, value);
        }

        private async void DoWork(object sender, DoWorkEventArgs e)
        {

            if (isConnectionReady())
            {
                try
                {
                    if (Method.ToLower() == "post")
                    {
                        response = await client.PostAsync(new Uri(uploadURL, UriKind.Absolute), httpContent);
                    }
                    else if (Method.ToLower() == "push")
                    {
                        response = await client.PutAsync(new Uri(uploadURL, UriKind.Absolute), httpContent);
                    }


                    // DO SOMETHING WITH THE RESPONSE HERE


                }
                catch (Exception)
                {

                    //UPDATE THE UI THREAD HERE
                    Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        MessageBox.Show("Upload did not complete successfully. Check your connection settings.", "Something Went Wrong", MessageBoxButton.OK);
                    }));
                }


            }
            else
            {
                //UPDATE THE UI THREAD HERE
                Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    MessageBox.Show("Check your phone's connection settings", "No Network Connection", MessageBoxButton.OK);
                }));
            }
        }


        // METHOD USED TO CHECK FOR NETWORK CONNECTION
        private bool isConnectionReady()
        {
            bool internet = false;

            //Check if network is available
            if (DeviceNetworkInformation.IsNetworkAvailable)
            {
                internet = true;
            }

            return internet;
        }

    }
}

// THIS METHOD IS ACTIVATED IN THE SIGNUP BUTTON EVENT HANDLER
public void SendToServer()
{
          //  string user = JsonConvert.SerializeObject(App.ViewModel.Users[0]); // Get User Information 

            TestUser me = new TestUser() { Name="testName2", Password="password",Email="mail@mail.com"};
            me.Roles.Add("User");
            string meString = JsonConvert.SerializeObject(me);

            if (App.Settings.Contains("FirstSignUp"))
            {
                service = new UploadJsonService(ConnectToServer.USER_UPLOAD_URL,"PUT",meString);
            }
            else
            {
                service = new UploadJsonService(ConnectToServer.USER_UPLOAD_URL,"POST",meString);
            }

            service.SetHeader("Authorization", "Basic " + ConnectToServer.Get64BitEncoding(ConnectToServer.SERVER_ADMIN));

            service.GetBackGroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(RunWorkerServiceCompleted);
            service.StartUpload();
}

 private void RunWorkerServiceCompleted(object sender, RunWorkerCompletedEventArgs e)
{
 // DO WORK AFTER THE BACKGROUND WORKER COMPLETES
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JailBird_ProtoType.Services
{
    // THIS CLASS HOLDS ALL SERVER INFORMATION
    // FOR QUICK ACCESS AND CHANGE
    public static class ConnectToServer
    {
        public static string SERVER_ADMIN = "admin:password";

        // UPLOAD USER TO DB

        public static string USER_UPLOAD_URL = "https://xx.xxx.xx.xxx:443/api/users";




        public static string Get64BitEncoding(string key) {
            byte[] convert = System.Text.Encoding.UTF8.GetBytes(key);
            return System.Convert.ToBase64String(convert);
        }
    }
}
出于安全原因,

省略了真实的服务器地址。

抱歉,我的代码结构不正确。正在改变它以使其发挥作用。

0 个答案:

没有答案