Перевести запрос PHP Json Webservice в VB.Net Запрос Json Webservice - PullRequest
1 голос
/ 13 июня 2011

Я прошу помощи, потому что я пробовал 1000 решений, и никто не работал со мной, возможно, потому что я не очень хорошо знаю JSON и PHP Я должен отправить запрос в Webservice, и у меня есть работающее решение PHP, которое я должен перевести на VB.net

Вот код, работающий в PHP

//fill in the details of the contacts.userId is obtained from loginResult.
$contactData  = array('lastname'=>'Valiant', 'assigned_user_id'=>$userId);
//encode the object in JSON format to communicate with the server.
$objectJson = Zend_JSON::encode($contactData);
//name of the module for which the entry has to be created.
$moduleName = 'Contacts';

//sessionId is obtained from loginResult.
$params = array("sessionName"=>$sessionId, "operation"=>'create', 
    "element"=>$objectJson, "elementType"=>$moduleName);
//Create must be POST Request.
$httpc->post("$endpointUrl", $params, true);
$response = $httpc->currentResponse();
//decode the json encode response from the server.
$jsonResponse = Zend_JSON::decode($response['body']);

//operation was successful get the token from the reponse.
if($jsonResponse['success']==false)
    //handle the failure case.
    die('create failed:'.$jsonResponse['error']['errorMsg']);
$savedObject = $jsonResponse['result'];
$id = $savedObject['id'];

Хорошо, а вот мой код в VB.net

Структура контактных данных Публичная фамилия As String Общедоступный assign_user_id As String Конечная структура

Try Dim uri As New Uri ("webservice.php")

        Dim contactdata As New Contactdata
        contactdata.lastname = "Valiant"
        contactdata.assigned_user_id = "19x1"

        Dim objectJson As String = JavaScriptConvert.SerializeObject(contactdata)

        Dim moduleName As String = "Contacts"

        Dim params As String() = {"sessionName=" & session, "operation=create", "element=" & objectJson, "elementType=" & moduleName}

        Dim request As HttpWebRequest = HttpWebRequest.Create(uri)
        request.Method = WebRequestMethods.Http.Post
        request.ContentLength = params.Length
        request.ContentType = "application/x-www-form-urlencoded"

        Dim writer As New StreamWriter(request.GetRequestStream)
        writer.Write(params)
        writer.Close()
        Dim oResponse As HttpWebResponse = request.GetResponse()
        Dim reader As New StreamReader(oResponse.GetResponseStream())
        Dim tmp As String = reader.ReadToEnd()
        oResponse.Close()


    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try

Естественно, я импортировал ссылку на библиотеку Json и импортировал (Imports Newtonsoft.Json) Это не проблема, я уверен, что я делаю что-то не так с параметрами.

Кто-нибудь может мне помочь с этим?

1 Ответ

0 голосов
/ 14 июня 2011

Вот рабочий код

В модуле

Structure Contactdata
Public lastname As String
Public assigned_user_id As String
End Structure

Тогда в моей форме

Imports Newtonsoft.Json



Dim contactdata As New Contactdata
contactdata.lastname = "Valiant"
contactdata.assigned_user_id = "19x1"

Dim objectJson As String = JavaScriptConvert.SerializeObject(contactdata)

Dim moduleName As String = "Contacts"

Dim params As String = "sessionName=" & session & "&operation=create" & "&element=" & objectJson & "&elementType=" & moduleName

Dim request As HttpWebRequest = HttpWebRequest.Create(uri)
request.Method = WebRequestMethods.Http.Post
request.ContentLength = params.Length
request.ContentType = "application/x-www-form-urlencoded"

Dim writer As New StreamWriter(request.GetRequestStream)
writer.Write(params)
writer.Close()
Dim oResponse As HttpWebResponse = request.GetResponse()
Dim reader As New StreamReader(oResponse.GetResponseStream())
Dim tmp As String = reader.ReadToEnd()
oResponse.Close()


Catch ex As Exception
MsgBox(ex.ToString)
End Try
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...