我知道这些主题在stackoverflow上存在很多。 但我有一个不同的问题:
我创建了一个DataContract类,如下所示:
[DataContract]
public class GLSParcelClass {
internal string Location;
internal string ConsignmentId;
internal string Labels;
internal List<Parcels> ParcelList;
internal List<Returns> ReturnList;
}
[DataContract]
public class Parcels {
internal string Location;
internal string TrackId;
internal string ParcelNumber;
}
[DataContract]
public class Returns {
internal string Location;
internal string TrackId;
internal string ParcelNumber;
}
然后我写了以下函数:
WebRequest httpWebRequest = WebRequest.Create(this.GLSUri);
string json = "{" +
"\"shipperId\":\"2764200001 276a165X14\"," +
"\"references\":[\"47110815\"]," +
"\"addresses\":{" +
"\"delivery\":{" +
"\"name1\":\"Max Meyer\"," +
"\"name2\":\"Meyer Ltd.\"," +
"\"street1\":\"Meyer Str. 227\"," +
"\"street2\":\"2. Floor\"," +
"\"country\":\"DE\"," +
"\"zipCode\":\"92753\"," +
"\"city\":\"Passau\"," +
"\"email\":\"maxmeyer@gmail.com\"}}," +
"\"parcels\":[" +
"{" +
"\"weight\":2.5," +
"\"references\":[" +
"\"47110815\"]" +
"}" +
"]" +
"}";
httpWebRequest.ContentType = "application/json";
Type type = httpWebRequest.Headers.GetType();
System.Reflection.BindingFlags flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
System.Reflection.MethodInfo m = type.GetMethod("AddWithoutValidate", flags);
m.Invoke(httpWebRequest.Headers, new string[] { "Accept", "application/json" });
m.Invoke(httpWebRequest.Headers, new string[] { "Accept-Language", "de" });
m.Invoke(httpWebRequest.Headers, new string[] { "Accept-Encoding", "gzip,deflate" });
httpWebRequest.Method = "POST";
string lsEncodedCred = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("utf-8").GetBytes("shipmentsapi" + ":" + "shipmentsapi"));
httpWebRequest.Headers.Add("Authorization", "Basic " + lsEncodedCred);
httpWebRequest.PreAuthenticate = true;
StreamWriter streamWriter = null;
using (streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) {
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader loStream = new StreamReader(httpResponse.GetResponseStream())) {
GLSParcelClass deserializedParcels = new GLSParcelClass();
string lsJSON = loStream.ReadToEnd();
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(lsJSON));
DataContractJsonSerializer ser = new DataContractJsonSerializer(deserializedParcels.GetType());
deserializedParcels = ser.ReadObject(ms) as GLSParcelClass;
ms.Close();
}
我得到了答案&#34;创建&#34;响应标头中的JSON API的状态码为201。到现在为止还挺好。但是当我得到ResponseStream时,我得到错误&#34; System.Runtime.Serialization.SerializationException - 反序列化对象时出错。意外的字符&#34;。&#34;。&#34; 。
备选方案我已经使用Mozilla REST客户端对其进行了测试。我将使用正确的响应流获得正确的标头。
响应流还包括base64字符串编码的pdf文档。
我真的不知道什么是错的,我希望你能帮助我。
提前很多。
米洛
答案 0 :(得分:0)