Połączenie API do sklepu RedCart C# (vb.net)

0

Dzień dobry

Pomógłby mi ktoś w przepisaniu poniższego kodu w Phytonie na C# VB.net ? Oczywiście może być z wykorzystaniem newtonsoft json
Próbowałam już na wiele sposobów i cały czas mi zwraca komunikat o błędnym json
Za pomocą Postmana dostaję prawidłową odpowiedź

Kod w Phytonie:

import urllib
import urllib2
import simplejson as json
data = {
 'key' : 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
 'viewType' : 'json',
 'module' : 'hello',
 'method' : 'hello',
 'parameters' : {'name': 'redcart'}
}
jsonData = {'json' : json.dumps(data)}
postData = urllib.urlencode(jsonData)
req = urllib2.Request("http://api2.redcart.pl/?input=json",postData)
opener = urllib2.build_opener()
f = opener.open(req)
result = json.load(f) 
print(result)

Aneta

1

@AnetaZ: wrzuć napisany kod ;)

0

Imports Newtonsoft.Json
Imports System.Net
Imports System.Text
Imports SoftHelp
Imports System.IO
Imports System.Net.Http
Imports System.Runtime.CompilerServices
Imports Newtonsoft.Json.Linq
Imports System.Globalization

Public Class JsonGet
    Public json As GetOrders = New GetOrders
End Class

Public Class GetOrders
    Public key As String = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    Public viewType As String = "json"
    Public [module] As String = "hello"
    Public method As String = "hello"
    Public parameters As New Parameters
End Class

Public Class Parameters
    Public name As String = "RED CART"
End Class

Private Async Sub Test()
       Dim RestURL As String = "http://api2.redcart.pl?input=json"
       Dim client As New Http.HttpClient
       Dim JsonData As String
       Dim RestContent As Net.Http.StringContent
       Dim RestResponse As Net.Http.HttpResponseMessage

       Try
           Dim json As JsonGet = New JsonGet
           JsonData = JsonConvert.SerializeObject(json)
           Console.WriteLine(JsonData)
           'Tutaj mam: 
           '{"json":{"key":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxx","viewType":"json","module":"hello","method":"hello","parameters":{"name":"RED CART"}}}
           RestContent = New Net.Http.StringContent(JsonData, Encoding.UTF8, "application/json")
           RestResponse = Await client.PostAsync(RestURL, RestContent)
           Dim result As String = Await RestResponse.Content.ReadAsStringAsync
           Console.Write(result)
           'A tutaj: 
           '{"error":{"code":"E_INPUT_JSON","message":"B\u0142\u0119dny json "},"request":null}
       Catch ex As Exception
           MessageBox.Show(ex.Message)
       End Try
   End Sub

Albo w c#

using Newtonsoft.Json;
using System;
using System.Text;
using System.Windows.Forms;
using System.Net.Http;

namespace RedCartApi
{    
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            Test();
        }
        private async void Test()
        {
            string RestURL = "http://api2.redcart.pl?input=json";
            HttpClient client = new HttpClient();
            string JsonData;
            StringContent RestContent;
            HttpResponseMessage RestResponse;

            try
            {
                JsonGet json = new JsonGet();
                JsonData = JsonConvert.SerializeObject(json);
                Console.WriteLine(JsonData);
                 // Tutaj mam: 
                // {"json":{"key":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxx","viewType":"json","module":"hello","method":"hello","parameters":{"name":"RED CART"}}}
                RestContent = new System.Net.Http.StringContent(JsonData, Encoding.UTF8, "application/json");
                RestResponse = await client.PostAsync(RestURL, RestContent);
                string result = await RestResponse.Content.ReadAsStringAsync();
                Console.Write(result);
                // A tutaj: 
                // {"error":{"code":"E_INPUT_JSON","message":"B\u0142\u0119dny json "},"request":null}    
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
    public class JsonGet
    {
        public GetOrders json = new GetOrders();
    }

    public class GetOrders
    {
        public string key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
        public string viewType = "json";
        public string module = "hello";
        public string method = "hello";
        public Parameters parameters = new Parameters();
    }

    public class Parameters
    {
        public string name = "RED CART";
    }
}


0

z
https://redcart.pl/doc/redcart.pl_dokumentacja_api.pdf

parameters (array)
tablica parametrów (pól) bazy danych
np. array('products_id' => 100, 'products_name' => 'Pralka J23')

czyli musisz zrobić tablicę, a nie obiekt dla parametrów

czyli np

paramters[
{"key1":"value1"},
{"key2":"value2"}
]
0

W Pythonie (przerobiłam trochę to co jest w dokumentacji a ja zamieściłam na początku wątku) piszę tak :

import urllib
import urllib.parse
import urllib.request
import json 
from json import JSONEncoder

class Parameters:
    def __init__(self, name):
        self.name = name

class Sayhelo:
    def __init__(self, key, viewType, module, method, parameters):
            self.key=key
            self.viewType=viewType
            self.module=module
            self.method=method
            self.parameters=parameters

    
# subclass JSONEncoder
class encoder(JSONEncoder):
        def default(self, o):
            return o.__dict__


parameters=Parameters("RED CART")
sayhelo=Sayhelo("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","json","hello","hello",parameters)       
jsonData = {"json" : json.dumps(sayhelo,indent=None, cls=encoder)}
print()
print(jsonData)
postData = urllib.parse.urlencode(jsonData)
data = postData.encode('utf-8')
print()
print(data)
req = urllib.request.Request("http://api2.redcart.pl/?input=json", data=data)
r = urllib.request.urlopen(req)
content = r.read().decode()
print()
print(content) 


request wygląda następująco:

{'json': '{"key": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "viewType": "json", "module": "hello", "method": "hello", "parameters": {"name": "RED CART"}}'}

i odpowiedź jest prawidłowa, więc to raczej nie o parametry chodzi

1 użytkowników online, w tym zalogowanych: 0, gości: 1