0

I am currently trying to get a correct VB.NET (or C#) code fragment for doing a LOGIN on astrometry.net. The procedure is described here: https://nova.astrometry.net/api_help and https://astrometry.net/doc/net/api.html

  • I tried a lot of things, but the best I get is {"status": "error", "errormessage": "no json"}
  • If I press the button on the web page with a wrong API key the site response is: {"status": "error", "errormessage": "bad apikey"}. Getting this in my code would already be enough.

This is my current fragment:

Dim LoginURL As String = "http://nova.astrometry.net/api/login"

Dim Enc As System.Text.Encoding = System.Text.Encoding.UTF8
Dim MediaType As String = "application/json"
Dim JSONContent As String = "{""apikey"": """ & APIKey & """}"

Dim C2String As New System.Net.Http.StringContent(JSONContent , Enc, MediaType)

'Run the query
Dim MyClient As New System.Net.Http.HttpClient
Dim F As System.Net.Http.HttpResponseMessage = Await MyClient.PostAsync(LoginURL, C2String)
Dim Code As String = Await F.Content.ReadAsStringAsync()

I think I miss some parameter to indicate that the query is in JSON format, but I have no idea where.

Any hints?

Best regards Martin

1

1 Answer 1

1

You need to make a few changes to make this work.

First, encode the value of the JSONContent variable by using the System.Web.HttpUtility class:

Dim JSONContent As String = System.Web.HttpUtility.UrlEncode("{""apikey"": """ & APIKey & """}")

Then prepend the request-json= string as noted in the documentation:

JSONContent = "request-json=" & JSONContent

Lastly, set the correct content type on the StringContent object:

Dim C2String As New System.Net.Http.StringContent(JSONContent , Enc, "application/x-www-form-urlencoded")

I tested this myself and it works. Please check the VB.NET syntax. I am a C# developer so I did my best to properly translate it.

Sign up to request clarification or add additional context in comments.

2 Comments

In addition, OP should use a JSON serializer to create their JSON, in case any of the characters in APIKey need escaping. E.g. System.Text.Json.JsonSerializer.Serialize(New With {.apikey = APIKey }). See e.g. How to use string interpolation and verbatim string together to create a JSON string literal? for a discussion why.
@dbc Great suggestion. In this case, the payload is exceedingly simple but in general, the recommendation would be to bulletproof the Json format as the key could contain special characters as you mentioned.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.