Json via Post an http webrequest und http basic authentication senden

  • VB.NET

Es gibt 9 Antworten in diesem Thema. Der letzte Beitrag () ist von Takafusa.

    Json via Post an http webrequest und http basic authentication senden

    Hallo,

    leider bin ich im Bezug auf Online-Anbindung der totale Anfänger und bekomme es leider nicht auf die Reihe. Ich habe eine ganz simple API, an die ich mich anbinden will. Daten von dort abholen via Webrequest habe ich hinbekommen.
    Ich muß nun aber an diese Seite via Post wiederrum ein JSON zurück senden, finde hier aber kein Beispiel, das für mich funktioniert. Ich bekomme in folgendem Code dann z.B. "Der Remoteserver hat einen Fehler zurückgegeben: (422) Unprocessable Entity" zurück. Das Json ist aber das Beispiel des Anbieters und auch valide

    VB.NET-Quellcode

    1. Dim postData As String = "{'customer_order_reference':'70000001','comments_customer':'Please deliver asap','addressbook':{'country':'FR'},'order_products':[{'product_code':'274181','quantity':1,'addressbook':{'address':'Covent Garden','address2':'','city':'London','province':'','postal_code':'NR33 7NL','country':'GB','name':'Test Company','phone':'0684541247','comments':''}},{'product_code':'99999','quantity':1,'addressbook':{'address':'Covent Garden','address2':'','city':'London','province':'','postal_code':'NR33 7NL','country':'GB','name':'Test Company','phone':'0684541247','comments':''}}]}"
    2. Dim credentials As NetworkCredential = New NetworkCredential("rs@xxx.de", "12345")
    3. Dim encoding As New UTF8Encoding
    4. Dim byteData As Byte() = encoding.GetBytes(postData)
    5. Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create("https://xxx.com/api_customer/orders"), HttpWebRequest)
    6. postReq.Method = "POST"
    7. postReq.KeepAlive = True
    8. postReq.Credentials = credentials
    9. postReq.ContentType = "application/x-www-form-urlencoded"
    10. postReq.Referer = ""
    11. postReq.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.3) Gecko/20100401 Firefox/4.0 (.NET CLR 3.5.30729)"
    12. postReq.ContentLength = byteData.Length
    13. Dim postreqstream As Stream = postReq.GetRequestStream()
    14. postreqstream.Write(byteData, 0, byteData.Length)
    15. postreqstream.Close()
    16. Dim postresponse As HttpWebResponse
    17. postresponse = DirectCast(postReq.GetResponse(), HttpWebResponse)
    18. Dim postreqreader As New StreamReader(postresponse.GetResponseStream())
    19. Dim thepage As String = postreqreader.ReadToEnd
    20. RichTextBox1.Text = thepage


    Anhand der Fehlermeldung gehe ich eigentlich davon an, das die Verbindung zumind. soweit zustande kommt und ehr die Daten das Problem sind. Ist aber 1:1 das Beispiel aus der minimalistischen Doku.

    Kann mir jemand verraten, ob der Code hier grundsätzlich wohl richtig ist bzw. ich hier ein unpassendes Beispiel angepasst habe?
    "Unprocessable Entity" bedeutet das der Server die Daten nicht verarbeiten konnte.
    Ich denke das Problem hier ist, dass du einfach-Anführungszeichen verwendest, JSON akzeptiert nur ".
    ----------------------------------------------------------------------------------------------------------------------

    Hier könnte meine Signatur stehen, aber die ist mir abfußen gekommen.

    ----------------------------------------------------------------------------------------------------------------------
    @Superuse Hi, ist die API öffentlich zugänglich / Freikontingent etc.. Falls ja -> poste doch die Seite der API inkl. Dokumentation. Dann kann der, der das will es nachbauen/versuchen. Geht natürlich nur wenn das nicht 'geheim/verboten' ist :)
    codewars.com Rank: 4 kyu
    Die Api-Dokumentation ist leider mehr als spärlich. Hierzu gibt es nur diese Beschreibung:

    Note:

    The limit is maximum 120 requests per minute and maximum 500 products per request.

    Authentication

    Authentication is HTTP Basic authentication with username equal to
    the customer's email and password the API token of the customer

    Method 1: Get all products (that you are allowed to sell).
    Description
    Get all products (that you are allowed to sell)
    Action
    GET
    URL
    /api_customer/products

    Sample response
    [
    {
    "id": 4,
    "name": "Cat Tree 182 cm Beige Plush",
    "code": "100058",
    "category_path": "Animals & Pet Supplies/Pet Supplies/Cat Supplies/Cat Furniture",
    "quantity": "0.0",
    "price": "75.00",
    "created_at": "2017-09-18T10:25:58.000+02:00",
    "updated_at": "2019-03-27T13:58:51.000+01:00"
    },
    {
    "id": 5,
    "name": "Triangular Hammock for Hamsters",
    "code": "100074",
    "category_path": "Animals & Pet Supplies/Pet Supplies/Small Animal Supplies/Small Animal Habitat Accessories",
    "quantity": "0.0",
    "price": "4.90",
    "created_at": "2017-09-18T10:25:59.000+02:00",
    "updated_at": "2018-10-30T10:37:40.000+01:00"
    }
    ]

    Das war alles.

    Ich hab jetzt mal die Hochkommas durch Chr(34) ersetzt. Lesbarer wird es dadurch definitiv aber nicht. Fehler bleibt danach der gleiche.

    {" & Chr(34) & "customer_order_reference" & Chr(34) & ":" & Chr(34) & "70000001" & Chr(34) & "," & Chr(34) & "comments_customer" & Chr(34) & ":" & Chr(34) & "Please deliver asap" & Chr(34) & "," & Chr(34) & "addressbook" & Chr(34) & ":{" & Chr(34) & "country" & Chr(34) & ":" & Chr(34) & "FR" & Chr(34) & "}," & Chr(34) & "order_products" & Chr(34) & ":[{" & Chr(34) & "product_code" & Chr(34) & ":" & Chr(34) & "274181" & Chr(34) & "," & Chr(34) & "quantity" & Chr(34) & ":1," & Chr(34) & "addressbook" & Chr(34) & ":{" & Chr(34) & "address" & Chr(34) & ":" & Chr(34) & "Covent Garden" & Chr(34) & "," & Chr(34) & "address2" & Chr(34) & ":" & Chr(34) & "" & Chr(34) & "," & Chr(34) & "city" & Chr(34) & ":" & Chr(34) & "London" & Chr(34) & "," & Chr(34) & "province" & Chr(34) & ":" & Chr(34) & "" & Chr(34) & "," & Chr(34) & "postal_code" & Chr(34) & ":" & Chr(34) & "NR33 7NL" & Chr(34) & "," & Chr(34) & "country" & Chr(34) & ":" & Chr(34) & "GB" & Chr(34) & "," & Chr(34) & "name" & Chr(34) & ":" & Chr(34) & "Test Company" & Chr(34) & "," & Chr(34) & "phone" & Chr(34) & ":" & Chr(34) & "0684541247" & Chr(34) & "," & Chr(34) & "comments" & Chr(34) & ":" & Chr(34) & "" & Chr(34) & "}},{" & Chr(34) & "product_code" & Chr(34) & ":" & Chr(34) & "99999" & Chr(34) & "," & Chr(34) & "quantity" & Chr(34) & ":1," & Chr(34) & "addressbook" & Chr(34) & ":{" & Chr(34) & "address" & Chr(34) & ":" & Chr(34) & "Covent Garden" & Chr(34) & "," & Chr(34) & "address2" & Chr(34) & ":" & Chr(34) & "" & Chr(34) & "," & Chr(34) & "city" & Chr(34) & ":" & Chr(34) & "London" & Chr(34) & "," & Chr(34) & "province" & Chr(34) & ":" & Chr(34) & "" & Chr(34) & "," & Chr(34) & "postal_code" & Chr(34) & ":" & Chr(34) & "NR33 7NL" & Chr(34) & "," & Chr(34) & "country" & Chr(34) & ":" & Chr(34) & "GB" & Chr(34) & "," & Chr(34) & "name" & Chr(34) & ":" & Chr(34) & "Test Company" & Chr(34) & "," & Chr(34) & "phone" & Chr(34) & ":" & Chr(34) & "0684541247" & Chr(34) & "," & Chr(34) & "comments" & Chr(34) & ":" & Chr(34) & Chr(34) & "}}]}
    Ich habe bisher nicht mit vielen Web-APIs gearbeitet, aber ich habe es noch nicht erlebt, das man selbst einen JSON senden musste, meist waren es einfache Parameter die via GET oder POST gesendet werden mussten. Ich würde gerne mal die Webseite der Doku sehen, auch wenn diese spärlich dokumentiert ist. Sonst kann ich nicht helfen.
    Sorry. Hatte die falsche API Beschreibung geschickt. Das falsche war mit GET. Das hab ich zum laufen bekommen. Hier die andere Beschreibung:

    Note

    1.Order payment is not available via API. All the accepted orders are
    available in Unsubmitted orders. You have to manually pay for orders
    there.

    2.The limit is maximum 1 requests per second.
    Authentication

    Authentication is HTTP Basic authentication with username equal to
    the customer's email and password the API token of the customer
    customer_id OR customer_email fields are not required in the request because they are set based on the authenticated user

    Header
    Content-Type: application/json

    Create Order

    Description Create Order

    Action POST

    URL
    /api_customer/orders
    Sample request parameters

    {
    "customer_order_reference": "70000001",
    "comments_customer":"Please deliver asap",
    "addressbook":{
    "country":"FR" },
    "order_products":[
    {
    "product_code":"274181",
    "quantity":1,
    "addressbook":{
    "address":"Covent Garden",
    "address2":"",
    "city":"London",
    "province": "",
    "postal_code":"NR33 7NL",
    "country":"GB",
    "name":"Test Company",
    "phone": "0684541247",
    "comments":""
    }
    },

    {
    "product_code":"99999",
    "quantity":1,
    "addressbook":{
    "address":"Covent Garden",
    "address2":"",
    "city":"London",
    "province": "",
    "postal_code":"NR33 7NL",
    "country":"GB",
    "name":"Test Company",
    "phone": "0684541247",
    "comments":""
    }
    }
    ]
    }

    Wie kann ich so etwas über den Browser wegschicken?

    Edit:

    Hab aufgrund deines Postings mal etwas gegoogled und bin auf Reqbin.com gestoßen. Dort konnte ich den Request erfolgreich absenden und habe auch eine Antwort dazu bekommen.

    Dort kann man sich wiederum zumind. C# Code zurück bekommen. Den teste ich nun konvertiert als VB.NET. Was aber wohl richtig "grausam" ist, ist das JSON als String mit Anführungszeichen zu bauen ;(

    Edit:

    Hab das nun gelöst:

    So läuft es:

    VB.NET-Quellcode

    1. Private Sub SurroundingSub()
    2. Dim url = "https://xxx.com/api_customer/orders"
    3. Dim httpRequest = CType(WebRequest.Create(url), HttpWebRequest)
    4. Dim Response As String = ""
    5. httpRequest.Method = "POST"
    6. httpRequest.Headers("Authorization") = "Basic blablabla"
    7. httpRequest.ContentType = "application/json"
    8. Dim data = "{""customer_order_reference"":""70000001"",""comments_customer"":""Please deliver asap"",""addressbook"":{""country"":""FR""},""order_products"":[{""product_code"":""247825"",""quantity"":1,""addressbook"":{""address"":""Covent Garden"",""address2"":"""",""city"":""London"",""province"":"""",""postal_code"":""91717"",""country"":""DE"",""name"":""Test Company"",""phone"":""0684541247"",""comments"":""""}},{""product_code"":""247825"",""quantity"":1,""addressbook"":{""address"":""Covent Garden"",""address2"":"""",""city"":""London"",""province"":"""",""postal_code"":""91717"",""country"":""DE"",""name"":""Test Company"",""phone"":""0684541247"",""comments"":""""}}]}"
    9. Dim encoding As New UTF8Encoding
    10. Dim byteData As Byte() = Encoding.GetBytes(data)
    11. Using requestStream = httpRequest.GetRequestStream
    12. requestStream.Write(byteData, 0, byteData.Length)
    13. requestStream.Close()
    14. Using responseStream = httpRequest.GetResponse.GetResponseStream
    15. Using reader As New StreamReader(responseStream)
    16. Response = reader.ReadToEnd()
    17. End Using
    18. End Using
    19. End Using
    20. MsgBox(Response)
    21. End Sub


    Dieser Beitrag wurde bereits 3 mal editiert, zuletzt von „Superuse“ ()