本文目錄一覽:
- 1、如何用c實現http post json
- 2、用c#發送一個post類型的json包
- 3、Post請求json對象轉義問題
- 4、求一個c#的 post請求 json 並且接收返回json數據的一個demo。
- 5、如何從post json數據到網站
如何用c實現http post json
http是基於Socket通信的一種通信規約,post是http規約的一種功能,json是常用於字符串解釋型編程語言及一些腳本上用的對象格式。
用c#發送一個post類型的json包
HttpWebRequest req = WebRequest.CreateHttp(url);
var buffer = Encoding.UTF8.GetBytes(formData);
req.Method = “POST”;
req.ContentType = “application/json”;
req.ContentLength = buffer.Length;
using (var fs = req.GetRequestStream())
{
fs.Write(buffer, 0, buffer.Length);
fs.Flush();
}
WebResponse resp = null;
try
{
resp = req.GetResponse();
}
catch (WebException ex)
{
resp = ex.Response;
if (resp != null)
{
resp.Close();
}
throw;
}
var ns = resp.GetResponseStream();
Stream stream = ns;
if (e == null)
{
if (resp.SupportsHeaders)
{
var m = s_charsetRegex.Match(resp.ContentType);
if (m.Success)
{
e = Encoding.GetEncoding(m.Groups[1].Value);
}
var contentEncoding = resp.Headers.Get(“Content-Encoding”);
if (contentEncoding == “gzip”)
{
stream = new GZipStream(ns, CompressionMode.Decompress);
}
else if (contentEncoding == “deflate”)
{
stream = new DeflateStream(ns, CompressionMode.Decompress);
}
}
if (e == null)
{
e = Encoding.UTF8;
}
}
var reader = new StreamReader(stream, e);
System.Console.WriteLine(reader.ReadToEnd());需要引用System.Net
Post請求json對象轉義問題
/**
* 扁平化json格式
* {a:{b:{c:1}}} — {a.b.c=1}
* @param o
* @param prekey
* @param resobj
*/
function plat(o, prekey, resobj) {
const comType = [‘object’, ‘array’];
prekey = prekey ? prekey + ‘.’ : ”;
const keys = Object.keys(o);
keys.forEach((item) = {
const value = o[item];
const type = typeof value;
if (value comType.indexOf(type) !== -1) {
JsonUtil.plat(value, prekey + item, resobj);
} else {
resobj[prekey + item] = value;
}
})
};
var recordJson = {};
plat(values, ”, recordJson);
求一個c#的 post請求 json 並且接收返回json數據的一個demo。
public string HttpPost(string url,string data)
{
HttpWebRequest request=(HttpWebRequest)WebRequest.Create(url);
request.ContentType=”application/json”;
request.Method=”POST”;
byte[] buffer=Encoding.UTF8.GetBytes(data);
using(Stream stream=request.GetRequestStream())
{
stream.Write(buffer,0,buffer.Length);
}
HttpWebResponse response=(HttpWebResponse)request.GetResponse();
string result=string.Empty;
using(StreamReader reader=new StreamReader(response.GetResponseStream()))
{
result=reader.ReadToEnd();
}
return result;
}
如何從post json數據到網站
1. JSON的數據格式
a) 按照最簡單的形式,可以用下面這樣的 JSON 表示名稱/值對:
{ “firstName”: “Brett” }
b) 可以創建包含多個名稱/值對的記錄,比如:
{ “firstName”: “Brett”, “lastName”:”McLaughlin”, “email”: “brett@newInstance.com” }
c) 可以創建值的數組
{ “people”: [
{ “firstName”: “Brett”, “lastName”:”McLaughlin”, “email”: “brett@newInstance.com” },
{ “firstName”: “Jason”, “lastName”:”Hunter”, “email”: “jason@servlets.com” }
]}
d) 當然,可以使用相同的語法表示多個值(每個值包含多個記錄):
{ “programmers”: [
{ “firstName”: “Brett”, “lastName”:”McLaughlin”, “email”: “brett@newInstance.com” },
{ “firstName”: “Jason”, “lastName”:”Hunter”, “email”: “jason@servlets.com” }
],
“authors”: [
{ “firstName”: “Isaac”, “lastName”: “Asimov”, “genre”: “science fiction” },
{ “firstName”: “Tad”, “lastName”: “Williams”, “genre”: “fantasy” }
],
“musicians”: [
{ “firstName”: “Eric”, “lastName”: “Clapton”, “instrument”: “guitar” }
]
}
注意,在不同的主條目(programmers、authors 和 musicians)之間,記錄中實際的名稱/值對可以不一樣。JSON 是完全動態的,允許在 JSON 結構的中間改變表示數據的方式。
2. 在 JavaScript 中使用 JSON
JSON 是 JavaScript 原生格式,這意味着在 JavaScript 中處理 JSON 數據不需要任何特殊的 API 或工具包。
2.1 將 JSON 數據賦值給變量
例如,可以創建一個新的 JavaScript 變量,然後將 JSON 格式的數據字符串直接賦值給它:
var people =
{ “programmers”: [
{ “firstName”: “Brett”, “lastName”:”McLaughlin”, “email”: “brett@newInstance.com” },
{ “firstName”: “Jason”, “lastName”:”Hunter”, “email”: “jason@servlets.com” }
],
“authors”: [
{ “firstName”: “Isaac”, “lastName”: “Asimov”, “genre”: “science fiction” },
{ “firstName”: “Tad”, “lastName”: “Williams”, “genre”: “fantasy” }
],
“musicians”: [
{ “firstName”: “Eric”, “lastName”: “Clapton”, “instrument”: “guitar” }
]
}
2.2 訪問數據
將這個數組放進 JavaScript 變量之後,就可以很輕鬆地訪問它。實際上,只需用點號表示法來表示數組元素。所以,要想訪問 programmers 列表的第一個條目的姓氏,只需在JavaScript 中使用下面這樣的代碼:
people.programmers[0].lastName;
注意,數組索引是從零開始的。
2.3 修改 JSON 數據
正如訪問數據,可以按照同樣的方式修改數據:
people.musicians[1].lastName = “Rachmaninov”;
2.4 轉換回字符串
a) 在 JavaScript 中這種轉換也很簡單:
String newJSONtext = people.toJSONString();
b) 可以將任何 JavaScript 對象轉換為 JSON 文本。並非只能處理原來用 JSON 字符串賦值的變量。為了對名為 myObject 的對象進行轉換,只需執行相同形式的命令:
String myObjectInJSON = myObject.toJSONString();
說明:將轉換回的字符串作為Ajax調用的字符串,完成異步傳輸。
小結:如果要處理大量 JavaScript 對象,那麼 JSON 幾乎肯定是一個好選擇,這樣就可以輕鬆地將數據轉換為可以在請求中發送給服務器端程序的格式。
3. 服務器端的 JSON
3.1 將 JSON 發給服務器
a) 通過 GET 以名稱/值對發送 JSON
在 JSON 數據中會有空格和各種字符,Web 瀏覽器往往要嘗試對其繼續編譯。要確保這些字符不會在服務器上(或者在將數據發送給服務器的過程中)引起混亂,需要在JavaScript的escape()函數中做如下添加:
var url = “organizePeople.php?people=” + escape(people.toJSONString());
request.open(“GET”, url, true);
request.onreadystatechange = updatePage;
request.send(null);
b) 利用 POST 請求發送 JSON 數據
當決定使用 POST 請求將 JSON 數據發送給服務器時,並不需要對代碼進行大量更改,如下所示:
var url = “organizePeople.php?timeStamp=” + new Date().getTime();
request.open(“POST”, url, true);
request.onreadystatechange = updatePage;
request.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”);
request.send(people.toJSONString());
注意:賦值時格式必須是var msg=eval(‘(‘ + req.responseText + ‘)’);
3.2 在服務器上解釋 JSON
a) 處理 JSON 的兩步驟。
針對編寫服務器端程序所用的語言,找到相應的 JSON 解析器/工具箱/幫助器 API。
使用 JSON 解析器/工具箱/幫助器 API 取得來自客戶機的請求數據並將數據轉變成腳本能理解的東西。
b) 尋找 JSON 解析器
尋找 JSON 解析器或工具箱最好的資源是 JSON 站點。如果使用的是 Java servlet,json.org 上的 org.json 包就是個不錯的選擇。在這種情況下,可以從 JSON Web 站點下載 json.zip 並將其中包含的源文件添加到項目構建目錄。編譯完這些文件後,一切就就緒了。對於所支持的其他語言,同樣可以使用相同的步驟;使用何種語言取決於您對該語言的精通程度,最好使用您所熟悉的語言。
c) 使用 JSON 解析器
一旦獲得了程序可用的資源,剩下的事就是找到合適的方法進行調用。如果在 servlet 中使用的是 org.json 包,則會使用如下代碼:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { //report an error }
try {
JSONObject jsonObject = new JSONObject(jb.toString());
} catch (ParseException e) {
// crash and burn
throw new IOException(“Error parsing JSON request string”);
}
// Work with the data using methods like…
// int someInt = jsonObject.getInt(“intParamName”);
// String someString = jsonObject.getString(“stringParamName”);
// JSONObject nestedObj = jsonObject.getJSONObject(“nestedObjName”);
// JSONArray arr = jsonObject.getJSONArray(“arrayParamName”);
// etc…
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/239534.html