2017-04-15 21 views
-1

我需要幫助。 我的身體在編譯之前可以很好地處理數據。HttpWebRequest - 如何動態設置變量到本體中

Dim body As String = "{""travelForm"":[{""title"":""IT Unix 4"",""description"":""<p>Hello fjdsbfjsdhfkjn,vxnc bx vxnodjosidfjlkj kjk sds iufsyiufshkjdjxfoksjdkjfsiodhfsdhfsudhfskjdlfksjlfsjdkfhkjhjk hj hdkjfhksjdhfjkh kjh skjdhfkjsdhfkj hkjsdhfskjdskh jhsjdhfkjshdfjsdhkjfsdhkhsdkjsdhskjhfskjdhjshjdhfskjhskdhfkjdhfj hkjshdfsd</p>"",""phone"":""0199654128"",""categoryfont"":7459250,""categoryClass"":""Toyota"",""DataCategory"":100,""where"":{""latitude"":-33.8659683,""longitude"":18.534443499999952,""radius"":5000},""categoryAttributes"":[],""imageWeb"":[""c:\mypict100.JPG?set_id=8800005007""]}]}" 

但是當我嘗試設置變量dinamycally(Form3.txtbx_title.Text)象下面這樣,這是行不通的。

Dim body As String = "{""travelForm"":[{""title"":"&Form3.txtbx_title.Text&",""description"":""<p>Hello fjdsbfjsdhfkjn,vxnc bx vxnodjosidfjlkj kjk sds iufsyiufshkjdjxfoksjdkjfsiodhfsdhfsudhfskjdlfksjlfsjdkfhkjhjk hj hdkjfhksjdhfjkh kjh skjdhfkjsdhfkj hkjsdhfskjdskh jhsjdhfkjshdfjsdhkjfsdhkhsdkjsdhskjhfskjdhjshjdhfskjhskdhfkjdhfj hkjshdfsd</p>"",""phone"":""0199654128"",""categoryfont"":7459250,""categoryClass"":""Toyota"",""DataCategory"":100,""where"":{""latitude"":-33.8659683,""longitude"":18.534443499999952,""radius"":5000},""categoryAttributes"":[],""imageWeb"":[""c:\mypict100.JPG?set_id=8800005007""]}]}" 

請參閱完整的代碼如下

Imports System.Net 
 
Imports System.Text 
 
Imports System.IO 
 
Imports System.Diagnostics 
 
Imports System.IO.Compression 
 

 
Imports System.Net.WebUtility 
 

 

 
Module PostTravelForm 
 

 
    Public logincookiePost As CookieContainer 
 
    Dim logincookstring As String 
 

 
    Dim theWantedString As String 
 

 
    'Calls request functions sequentially. 
 
    Sub MakeRequests3() 
 
     Dim response As HttpWebResponse 
 
     Dim responseText As String 
 

 
     If Request_www_germany_com(response) Then 
 
      'Success, possibly use response. 
 
      responseText = ReadResponse(response) 
 

 
      response.Close() 
 
     Else 
 
      'Failure, cannot use response. 
 
     End If 
 
    End Sub 
 

 
    'Returns the text contained in the response. For example, the page HTML. Only handles the most common HTTP encodings. 
 
    Public Function ReadResponse(response As HttpWebResponse) As String 
 
     Using responseStream = response.GetResponseStream() 
 
      Dim streamToRead As Stream = responseStream 
 
      If response.ContentEncoding.ToLower().Contains("gzip") Then 
 
       streamToRead = New GZipStream(streamToRead, CompressionMode.Decompress) 
 
      ElseIf response.ContentEncoding.ToLower().Contains("deflate") Then 
 
       streamToRead = New DeflateStream(streamToRead, CompressionMode.Decompress) 
 
      End If 
 

 
      Using streamReader = New StreamReader(streamToRead, Encoding.UTF8) 
 
       Return streamReader.ReadToEnd() 
 
      End Using 
 
     End Using 
 
    End Function 
 
\t 
 
    ''' <summary> 
 
    ''' Tries to request the URL: https://www.travel.com/postad/create 
 
    ''' </summary> 
 
    ''' <param name="response">After the function has finished, will possibly contain the response to the request.</param> 
 
    ''' <returns>True if the request was successful; false otherwise.</returns> 
 
\t 
 
    Private Function Request_www_germany_com(ByRef response As HttpWebResponse) As Boolean 
 
     response = Nothing 
 

 
     Try 
 
      'Create request to URL. 
 
      Dim request As HttpWebRequest = DirectCast(WebRequest.Create("https://www.travel.com/api/postad/create"), HttpWebRequest) 
 
      Dim tempCookies As New CookieContainer 
 

 
      'Set request headers. 
 
      request.KeepAlive = True 
 
      request.Accept = "application/json, text/javascript, */*; q=0.01" 
 
      request.Headers.Add("Origin", "https://www.travel.com") 
 
      request.Headers.Add("x-requested-with", "XMLHttpRequest") 
 
      request.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36" 
 

 
      request.CookieContainer = logincookiePost 
 

 
      request.ContentType = "application/json" 
 
      request.Referer = "https://www.travel.com/post" 
 
      request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate, br") 
 
      request.Headers.Set(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.8") 
 

 
      'Set request method 
 
      request.Method = "POST" 
 

 
      ' Disable 'Expect: 100-continue' behavior. More info: http://haacked.com/archive/2004/05/15/http-web-request-expect-100-continue.aspx 
 
      request.ServicePoint.Expect100Continue = False 
 

 
      Console.WriteLine(Form3.txtbx_title.Text & " Test !!!!!!!!!!!!") 
 

 
      Dim txtbx As String = "<p>CISCO Senior Network Engineer</p>" 
 

 
      'Set request body. 
 
      
 
      Dim body As String = "{""ads"":[{""title"":""…" + txtbx + "…"",""description"":""<p>" + Form3.txtbx_descript.Text.Replace("""", "\""") + "</p>"",""phone"":""0799654128"",""categoryId"":9250,""categoryName"":""Computer Operators"",""parentCategory"":8,""location"":{""latitude"":-33.8659683,""longitude"":18.534443499999952,""radius"":2000},""categoryAttributes"":[],""imageUrls"":[""https://i.ebayimg.com/00/s/NjAwWDgwMA==/z/~qIAAOSwU8hY75kG/$_1.PNG?set_id=8800005007""]}]}" 
 

 

 
      Dim postBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(body) 
 
      request.ContentLength = postBytes.Length 
 
      Dim stream As Stream = request.GetRequestStream() 
 
      stream.Write(postBytes, 0, postBytes.Length) 
 
      stream.Close() 
 

 
      'Get response to request. 
 
      response = DirectCast(request.GetResponse(), HttpWebResponse) 
 
     Catch e As WebException 
 
      'ProtocolError indicates a valid HTTP response, but with a non-200 status code (e.g. 304 Not Modified, 404 Not Found) 
 
      If e.Status = WebExceptionStatus.ProtocolError Then 
 
       response = DirectCast(e.Response, HttpWebResponse) 
 
      Else 
 
       Return False 
 
      End If 
 
     Catch e As Exception 
 
      If response IsNot Nothing Then 
 
       response.Close() 
 
      End If 
 
      Return False 
 
     End Try 
 

 
     Return True 
 
    End Function 
 

 
End Module

+0

_「這行不通」_是一個非常模糊的問題描述。什麼/沒有發生?通過調用默認實例('Form3.Show()')打開'Form3',還是使用'New Form3'打開並調用'.Show()'? –

+0

From3.txtbx_title.Text只包含一個字符串。 Form3是主窗體。我也試過下面的Dim txtbx As String =「CISCO高級網絡工程師」Dim body As String =「{」「travelForm」「:[{」「title」「」「」「IT Unix 4」「,」&txtbx&「 :「」

Hello fjdsbfjsdhfkjn,vxnc bx vxnodjosidfjlkj kjk sds iufsyiufshkjdjxfoksjdkjhkjshdfsd

「」,「」phone「」:「」0199654128「」,「」categoryfont「」:7459250,「」categoryClass「」:「」Toyota「」「,」 「DataCategory」 「:100」, 「其中」 「:{」 「緯度」, 「: - 33.8659683」, 「經度」 「:18.534443499999952」, 「半徑」 「:5000}」, 「categoryAttributes」 「:[],」 「imageWeb」「:[」「c:\ mypict100.JPG?set_id = 8800005007」「]}]}」 –

+0

'Form3.txtbx_title.Text' **只能包含一個字符串!他問_ **它包含的是什麼(它的價值是什麼),而不是它包含的是什麼類型。 - 再次,請定義_「它不起作用」_。 –

回答

1

如果你研究的JSON syntax,你會發現,所有的對象鍵必須是字符串。這意味着,鑰匙必須用雙引號(")正確引用。因此,

{ CISCO Senior Network Engineer: "<p>Hello…</p>" } 

是無效的JSON,而

{ "CISCO Senior Network Engineer": "<p>Hello…</p>" } 

是有效的JSON。

你的問題似乎是你沒有引用密鑰。

措施編號:請注意,簡單地使用雙引號將Form3.txtbx_title.Text環繞是不夠的。您需要確保如果用戶輸入包含一個或多個雙引號的文本,則每個文本必須通過以\字符作爲前綴加以轉義。

+0

感謝您的評論。我真的知道我必須爲字符串加雙引號。但我擔心的是我必須動態加載數據。所以我必須像下面這樣使用變量:'Dim myVariable As String =「CISCO Senior Network Engineer」Dim body As String =「{」「travelForm」「:[{」「title」「:」&myVariable&「, 「」description「」:「」

Hello fjdsbfj iufsfsd

「」,「」phone「」:「」01 8「」,「catfont」「:7459250」,「categoryC lass」「:」「豐田 「」, 「」 DataCat 「」:100 「 」其中「」:{ 「」 緯度 「」:-33.8 「」 LON GIT中 「」:18.5 「」 半徑 「」:5 0},「」categoryAttri「」:[],「」imageWeb「」:[「」c:\ mypict10.JPG?set_id = 88「」]]]}「 ' –

+0

'」... 「+ myVariable +」...「'=>'」...「」「+ myVariable.Replace(」「」「」,「」「」)+「」「...」' – stakx

+0

謝謝你SOOOOOO MUCHHHHHHH先生stakx!我使用第二個作爲我的變量是一個字符串,所以它需要包含任何字符,包括引號和任何工作正常。無論我使用第二個,我不需要關心用戶輸入了嗎?或者某些字符不應該由用戶輸入?我感謝你的幫助先生。 –