java api http授权标头,HttpClient和设置授权标头

I'm trying to make a simple request to the Basecamp API, I'm following the instructions provided adding in a sample user agent and my credentials yet I keep getting a 403 Forbidden response back.

My credentials are definitely correct so is it a case of my request/credentials being set incorrectly?

This is what I have (removed personal info):

var httpClient = new HttpClient();

var content = new FormUrlEncodedContent(new[] { new KeyValuePair("User-Agent", "MyApp [EMAIL ADDRESS]") });

httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",

Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "[USERNAME]", "[PASSWORD]"))));

var response = await httpClient.PostAsync("https://basecamp.com/[USER ID]/api/v1/projects.json", content);

var responseContent = response.Content;

using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))

{

Console.WriteLine(await reader.ReadToEndAsync());

}

解决方案

A quick look over their documentation seems to indicate that the projects.json endpoint accepts the following in the body of the POST:

{

"name": "This is my new project!",

"description": "It's going to run real smooth"

}

You're sending the User-Agent as the POST body. I'd suggest you change your code as follows:

var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "[USERNAME]", "[PASSWORD]")));

using (var httpClient = new HttpClient())

{

httpClient.DefaultRequestHeaders.Add("User-Agent", "MyApp [EMAIL ADDRESS]");

httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);

var response = await httpClient.PostAsJsonAsync(

"https://basecamp.com/[USER ID]/api/v1/projects.json",

new {

name = "My Project",

description = "My Project Description"

});

var responseContent = await response.Content.ReadAsStringAsync();

Console.WriteLine(responseContent);

}

This posts the payload as specified in the docs and sets your user agent in the headers as it should be.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值