我必须通过Twitter API 1.1上传头像,但我总是得到422错误。 这是我的代码:
var path = "avatar.jpg";
var req = token.GetQueryWebRequest("https://api.twitter.com/1.1/account/update_profile_image.json", HttpMethod.POST);
ServicePointManager.Expect100Continue = false; /// ????????????
req.ContentType = "multipart/form-data";
var image = "image=" + Uri.EscapeDataString(getImageBase64Encode(path, 700));
var encode = Encoding.ASCII.GetBytes(image);
req.ContentLength = encode.Length;
var steam = req.GetRequestStream();
steam.Write(encode, 0, encode.Length);
var resp = req.GetResponse();
// ----------------
private string getImageBase64Encode(string filePath, int maxSize)
{
if (!File.Exists(filePath))
throw new Exception(string.Format("Файл не существует: {0}", filePath));
var file = new FileInfo(filePath);
if(file.Length > maxSize * 1024)
throw new Exception(string.Format("Файл слишком большой: {0}", filePath));
byte[] res = null;
try
{
res = File.ReadAllBytes(filePath);
}
catch (Exception)
{
throw new Exception(string.Format("Неудалось прочитать файл: {0}", filePath));
}
if (res == null)
{
throw new Exception(string.Format("Файл пуст или поврежден: {0}", filePath));
}
return Convert.ToBase64String(res);
}
GetQueryWebRequest - 使用oAuth标头获取请求
不提供框架
PS>对不起,我的英语太差了
答案 0 :(得分:0)
我解决了这个问题:
var imageByte = GetImageByte(path, 800);
var type = Path.GetExtension(path).Trim('.').ToLower();
var filename = Path.GetFileName(path);
if (type == "jpg") type = "jpeg";
if (type != "jpeg" && type != "png" && type != "gif") throw new Exception("Неверный формат файла для загрузки на сервер");
const string boundary = "--0246824681357ACXZabcxyz";
req.ContentType = string.Format("multipart/form-data; type=\"image/{0}\"; start=\"<banner>\"; boundary=\"{1}\"", type, boundary);
req.KeepAlive = true;
var image = string.Format(
"--{0}\r\n" +
"Content-Type: image/jpeg; name=\"banner\"\r\n" +
"Content-Transfer-Encoding: binary\r\n" +
"Content-ID: <image>\r\n" +
"Content-Disposition: form-data; name=\"banner\"; filename=\"{1}\"\r\n" +
"Content-Location: image\r\n" +
"\r\n", boundary, filename);
var encode = Encoding.UTF8.GetBytes(image);
var steam = req.GetRequestStream();
steam.Write(encode, 0, encode.Length);
steam.Write(imageByte, 0, imageByte.Length);
encode = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
steam.Write(encode, 0, encode.Length);
req.GetResponse();