我试图使用JSON . net与WebRequest,检索JSON使用"GET"。从本质上讲,我停留在解析部分并抓取要测试的项目上。WebResponse,如何使用WebResponse检索JSON文件?API.php是我连接到网站数据库登录的一种方式。如果登录成功,它返回一个JSON对象。
string sAddress = "http://hitsparkinteractive.com/api.php";
// Get the hash
string addrParams = "action=authenticate";
addrParams += "&username=" + user;
addrParams += "&password=" + pwd;
WebRequest webRequest = WebRequest.Create(sAddress + "?" + addrParams);
webRequest.Timeout = 3000;
WebResponse webResponse = webRequest.GetResponse();
JObject retJSON;
retJSON = JObject.Parse(webResponse.ToString());
这是Visual Basic 6中的工作代码,使用了WinHTTPRequest。
Private Function AuthenticateUser(ByVal index As Long, ByVal Username As String, ByVal Password As String) As Long
Dim HTTP As WinHttpRequest, sAddress As String, addrParams As String
Dim JSONParser As Object, retJSON As String, ErrorCode As String, ErrorMsg As String
On Error Resume Next
sAddress = "http://hitsparkinteractive.com/api.php"
addrParams = "action=authenticate"
addrParams = addrParams & "&username=" & Username
addrParams = addrParams & "&password=" & Password
Set HTTP = New WinHttpRequest
HTTP.Open "GET", sAddress & "?" & addrParams, False
HTTP.SetTimeouts 250, 250, 250, 3000
HTTP.Send
retJSON = HTTP.ResponseText
Set HTTP = Nothing
' Parse your JSON here.
Set JSONParser = JSON.parse(retJSON) ' What is returned is Scripting.Dictionary object
If Not JSONParser Is Nothing Then
If JSONParser.Exists("error") Then ' keys are case sensitive I believe
' We errored out
ErrorCode = JSONParser.Item("error")
Select Case ErrorCode
Case "3"
AuthenticateUser = 1
Case Else
AuthenticateUser = 2
End Select
ErrorMsg = JSONParser.Item("message")
Call AlertMsg(index, ErrorMsg)
Exit Function
ElseIf JSONParser.Exists("hash") Then ' we got our hash, sucessfully authenticated
TempPlayer(index).Hash = JSONParser.Item("hash")
AuthenticateUser = 0
Exit Function
End If
Else
AuthenticateUser = 3
Call AlertMsg(index, "Request timed out, please try again.")
Exit Function
End If
End Function
try this:
// Get the hash
string addrParams = string.Format("action=authenticate&username={0}&password={1}", user, pwd;)
string url = string.Concat(sAddress, "?", addrParams);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Timeout = 3000;
using (HttpWebResponse response = webRequest.GetResponse() as HttpWebResponse)
{
if (response.StatusCode == HttpStatusCode.OK) {
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(MyTypeJsonResponse));
object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
//json parsing response
MyTypeJsonResponse response = objResponse as Response;
}
}
[DataContract]
public class MyTypeJsonResponse
{
[DataMember(Name = "myProperty2")]
public string MyProperty1 { get; set; }
[DataMember(Name = "myProperty2")]
public string MyProperty2 { get; set; }
}
JSON实际上是一个字符串,表示序列化对象。
ToString
返回一个对象的字符串表示形式——可能类似于System.Web.HttpResponse
。
您需要的是响应的文本,您可以通过GetResponseStream
获得。