TML 幫助器用于修改 HTML 輸出。
HTML 幫助器
通過 MVC,HTML 幫助器類似于傳統的 ASP.NET Web Form 控件。
就像 ASP.NET 中的 Web Form 控件,HTML 幫助器用于修改 HTML。但是 HTML 幫助器是更輕量級的。與 Web Form 控件不同,HTML 幫助器沒有事件模型和視圖狀態。
在大多數情況下,HTML 幫助器僅僅是一個返回字符串的方法。
通過 MVC,您可以創建您自己的幫助器,或者直接使用內建的 HTML 幫助器。
標準的 HTML 幫助器
MVC 包含了大多數常用的 HTML 元素類型的標準幫助器,比如 HTML 鏈接和 HTML 表單元素。
HTML 鏈接
呈現 HTML 鏈接的最簡單的方法是使用 HTML.ActionLink() 幫助器。
通過 MVC,Html.ActionLink() 不連接到視圖。它創建一個連接到控制器操作。
Razor 語法:
@Html.ActionLink("About this Website", "About")
ASP 語法:
<%=Html.ActionLink("About this Website", "About")%>
第一個參數是鏈接文本,第二個參數是控制器操作的名稱。
上面的 Html.ActionLink() 幫助器,輸出以下的 HTML:
<a href="/Home/About">About this Website</a>
Html.ActionLink() 幫助器的一些屬性:
屬性 | 描述 |
---|---|
.linkText | URL 文本(標簽),定位點元素的內部文本。 |
.actionName | 操作(action)的名稱。 |
.routeValues | 傳遞給操作(action)的值,是一個包含路由參數的對象。 |
.controllerName | 控制器的名稱。 |
.htmlAttributes | URL 的屬性設置,是一個包含要為該元素設置的 HTML 特性的對象。 |
.protocol | URL 協議,如 "http" 或 "https"。 |
.hostname | URL 的主機名。 |
.fragment | URL 片段名稱(定位點名稱)。 |
注釋:您可以向控制器操作傳遞值。例如,您可以向數據庫 Edit 操作傳遞數據庫記錄的 id:
Razor 語法 C#:
@Html.ActionLink("Edit Record", "Edit", new {Id=3})
Razor 語法 VB:
@Html.ActionLink("Edit Record", "Edit", New With{.Id=3})
上面的 Html.ActionLink() 幫助器,輸出以下的 HTML:
<a href="/Home/Edit/3">Edit Record</a>
HTML 表單元素
以下 HTML 幫助器可用于呈現(修改和輸出)HTML 表單元素:
BeginForm()
EndForm()
TextArea()
TextBox()
CheckBox()
RadioButton()
ListBox()
DropDownList()
Hidden()
Password()
ASP.NET 語法 C#:
<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>
<% using (Html.BeginForm()){%>
<p>
<label for="FirstName">First Name:</label>
<%= Html.TextBox("FirstName") %>
<%= Html.ValidationMessage("FirstName", "*") %>
</p>
<p>
<label for="LastName">Last Name:</label>
<%= Html.TextBox("LastName") %>
<%= Html.ValidationMessage("LastName", "*") %>
</p>
<p>
<label for="Password">Password:</label>
<%= Html.Password("Password") %>
<%= Html.ValidationMessage("Password", "*") %>
</p>
<p>
<label for="Password">Confirm Password:</label>
<%= Html.Password("ConfirmPassword") %>
<%= Html.ValidationMessage("ConfirmPassword", "*") %>
</p>
<p>
<label for="Profile">Profile:</label>
<%= Html.TextArea("Profile", new {cols=60, rows=10})%>
</p>
<p>
<%= Html.CheckBox("ReceiveNewsletter") %>
<label for="ReceiveNewsletter" style="display:inline">Receive Newsletter?</label>
</p>
<p>
<input type="submit" value="Register" />
</p>
<%}%>
大家帶來的是Andoird基本UI控件中的RadioButton和Checkbox; 先說下本節要講解的內容是:RadioButton和Checkbox的
1.基本用法
2.事件處理;
3.自定義點擊效果;
4.改變文字與選擇框的相對位置;
5.修改文字與選擇框的距離
其實這兩個控件有很多地方都是類似的,除了單選和多選,事件處理,其他的都是類似的! 另外還有一個ListView上Checkbox的錯位的問題,我們會在ListView那一章對這個問題進行 解決,好的,開始本節內容~ 本節官方文檔API:RadioButton;CheckBox;
1.基本用法與事件處理:
1)RadioButton(單選按鈕)
如題單選按鈕,就是只能夠選中一個,所以我們需要把RadioButton放到RadioGroup按鈕組中,從而實現 單選功能!先熟悉下如何使用RadioButton,一個簡單的性別選擇的例子: 另外我們可以為外層RadioGroup設置orientation屬性然后設置RadioButton的排列方式,是豎直還是水平~
效果圖:
PS:筆者的手機是Android 5.0.1的,這里的RadioButton相比起舊版本的RadioButton,稍微好看一點~
布局代碼如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="請選擇性別"
android:textSize="23dp"
/>
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="@+id/btnMan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="男"
android:checked="true"/>
<RadioButton
android:id="@+id/btnWoman"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="女"/>
</RadioGroup>
<Button
android:id="@+id/btnpost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="提交"/>
</LinearLayout>
獲得選中的值:
這里有兩種方法,
第一種是為RadioButton設置一個事件監聽器setOnCheckChangeListener
例子代碼如下:
RadioGroup radgroup = (RadioGroup) findViewById(R.id.radioGroup);
//第一種獲得單選按鈕值的方法
//為radioGroup設置一個監聽器:setOnCheckedChanged()
radgroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radbtn = (RadioButton) findViewById(checkedId);
Toast.makeText(getApplicationContext(), "按鈕組值發生改變,你選了" + radbtn.getText(), Toast.LENGTH_LONG).show();
}
});
運行效果圖:
PS:另外有一點要切記,要為每個RadioButton添加一個id,不然單選功能會生效!!!
第二種方法是通過單擊其他按鈕獲取選中單選按鈕的值,當然我們也可以直接獲取,這個看需求~
例子代碼如下:
Button btnchange = (Button) findViewById(R.id.btnpost);
RadioGroup radgroup = (RadioGroup) findViewById(R.id.radioGroup);
//為radioGroup設置一個監聽器:setOnCheckedChanged()
btnchange.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
for (int i = 0; i < radgroup.getChildCount(); i++) {
RadioButton rd = (RadioButton) radgroup.getChildAt(i);
if (rd.isChecked()) {
Toast.makeText(getApplicationContext(), "點擊提交按鈕,獲取你選擇的是:" + rd.getText(), Toast.LENGTH_LONG).show();
break;
}
}
}
});
運行效果圖:
代碼解析: 這里我們為提交按鈕設置了一個setOnClickListener事件監聽器,每次點擊的話遍歷一次RadioGroup判斷哪個按鈕被選中我們可以通過下述方法獲得RadioButton的相關信息!
2)CheckBox(復選框)
如題復選框,即可以同時選中多個選項,至于獲得選中的值,同樣有兩種方式: 1.為每個CheckBox添加事件:setOnCheckedChangeListener 2.弄一個按鈕,在點擊后,對每個checkbox進行判斷:isChecked();
運行效果圖:
實現代碼:
public class MainActivity extends AppCompatActivity implements View.OnClickListener,CompoundButton.OnCheckedChangeListener{
private CheckBox cb_one;
private CheckBox cb_two;
private CheckBox cb_three;
private Button btn_send;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cb_one = (CheckBox) findViewById(R.id.cb_one);
cb_two = (CheckBox) findViewById(R.id.cb_two);
cb_three = (CheckBox) findViewById(R.id.cb_three);
btn_send = (Button) findViewById(R.id.btn_send);
cb_one.setOnCheckedChangeListener(this);
cb_two.setOnCheckedChangeListener(this);
cb_three.setOnCheckedChangeListener(this);
btn_send.setOnClickListener(this);
}
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(compoundButton.isChecked()) Toast.makeText(this,compoundButton.getText().toString(),Toast.LENGTH_SHORT).show();
}
@Override
public void onClick(View view) {
String choose = "";
if(cb_one.isChecked())choose += cb_one.getText().toString() + "";
if(cb_two.isChecked())choose += cb_two.getText().toString() + "";
if(cb_three.isChecked())choose += cb_three.getText().toString() + "";
Toast.makeText(this,choose,Toast.LENGTH_SHORT).show();
}
}
2.自定義點擊效果
雖然5.0后的RadioButton和Checkbox都比舊版本稍微好看了點,但是對于我們來說 可能還是不喜歡或者需求,需要自己點擊效果!實現起來很簡單,先編寫一個自定義 的selctor資源,設置選中與沒選中時的切換圖片~!
實現效果圖如下:
PS:這里素材的原因,有點小...
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_enabled="true"
android:state_checked="true"
android:drawable="@mipmap/ic_checkbox_checked"/>
<item
android:state_enabled="true"
android:state_checked="false"
android:drawable="@mipmap/ic_checkbox_normal" />
</selector>
寫好后,我們有兩種方法設置,也可以說一種吧!你看看就知道了~
①android:button屬性設置為上述的selctor
android:button="@drawable/rad_btn_selctor"
②在style中定義一個屬性,然后通過android style屬性設置,先往style添加下述代碼:
<style name="MyCheckBox" parent="@android:style/Widget.CompoundButton.CheckBox">
<item name="android:button">@drawable/rad_btn_selctor</item>
</style>
然后布局那里:
style="@style/MyCheckBox"
3.改變文字與選擇框的相對位置
這個實現起來也很簡單,還記得我們之前學TextView的時候用到的drawableXxx嗎? 要控制選擇框的位置,兩部即可!設置:
Step 1. android:button="@null"
Step 2. android:drawableTop="@android:drawable/btn_radio"
當然我們可以把drawableXxx替換成自己喜歡的效果!
4.修改文字與選擇框的距離
有時,我們可能需要調節文字與選擇框之間的距離,讓他們看起來稍微沒那么擠,我們可以:
1.在XML代碼中控制: 使用android:paddingXxx = "xxx" 來控制距離
2.在Java代碼中,稍微好一點,動態計算paddingLeft!
示例代碼如下:
rb.setButtonDrawable(R.drawable.rad_btn_selctor);
int rb_paddingLeft = getResources().getDrawable(R.mipmap.ic_checkbox_checked).getIntrinsicWidth()+5;
rb.setPadding(rb_paddingLeft, 0, 0, 0);
本節小結:
好的,關于RadioButton和Checkbox就講到這里,如果有什么寫得不對的,不好的,或者有好的建議歡迎指出 萬分感激
天內容好長,翻譯起來有點累。
Preparations
With the basics of HTTP out of the way, let's get acquainted with the tools we'll use in this book to demonstrate how HTTP works. This section goes through a few tools you'll need to follow along. Note that you only need one of the tools listed. It is important to note that you will be able to follow this book regardless of what tool you use, so pick one that you're comfortable with and get started!
翻譯:
準備工作,我們先學習下工具來演練 HTTP怎么工作的。本章節介紹下一些工具,可以選擇一個你覺得比較合適的來上手。
HTTP GUI Tools
We'll make heavy use of Graphical HTTP tools throughout this book. There are lots of options available in this category of HTTP tools, and we'll be using Paw 3. Although it's a paid App in the Mac App Store, there is a limited Trial version as well which can get you through the book.
That said, there are many other alternatives out there. Some other capable options are Insomnia and Postman; they're both free and they work on OS X, Windows, and Ubuntu.
HTTP 的 圖形用戶界面工具
我們這里用的是Paw3, 雖然他需要在蘋果商店買,但是也有短時間免費版本。
你也可以選擇 Insomnia 和 Postman (譯者之前裝過postman,這里就用Postman了)
HTTP Command line Tools
curl is a free command line tool that is used to issue HTTP requests.
Mac OS X/Linux :
It is shipped with OS X and most GNU/Linux distributions, and you can simply invoke it on the command line by issuing the command below.
$ curl www.google.com
If you have version 1803 or later of Windows 10, cURL should be installed by default. If you have an earlier version of windows or cannot find cURL on your version, we recommend installing a GUI version of cURL. You won't be able to execute the command line commands, but you should still be able to perform the appropriate actions in the GUI.
curl 是一個免費的工具,用來發送HTTP 請求,和MAC 及絕大多數 Linux 系統原生綁定。
你可以很簡單的啟動curl ,用下面命令行:
$ curl www.google.com
如果你有windows10的 1803 及以后版本,curl 也是默認安裝好了,如果你有更早的版本,你可以考慮安裝一個,圖形界面的curl. 你雖然沒法執行命令,但是可以在GUI 中執行相關操作。
Making HTTP Requests
HTTP Request with a Browser
Making an HTTP request is easy. Say you want to visit Reddit in your browser. All you need to do is launch your browser and enter the address https://www.reddit.com and
this is a snapshot of what you might see:
翻譯:
做HTTP的申請
通過一個瀏覽器做HTTP請求,做HTTP請求很容易,你可以在瀏覽器中訪問reddit ,直接鍵入地址https://www.reddit.com, 然后看到快照。
The server that hosts the main Reddit website handles your request and issues a response back to your browser. Your browser is smart enough to process the response that is sent back and display the site you see in the screenshot, with all its colors, images, text and presentation.
翻譯:
承載著Reddit web主站的服務器負責處理請求,并返回一個response 到瀏覽器,瀏覽器足夠“聰明”可以處理返回的響應文件,在屏幕上把文件展示出來,包含的是顏色、圖片、文字和展示。
HTTP Request with an HTTP Tool
Because browsers show us the processed version of the response, we don't get to see the raw response the server sent back. How do we see the raw HTTP response data?
For that, we can use an HTTP tool and just like the browser did when we entered a URL in the address bar, we can have our HTTP tool issue a request to https://www.reddit.com.
Our HTTP tool, Paw, doesn't process the response and lets us see the raw response data, which looks something like this:
通過工具來做HTTP請求
因為瀏覽器顯示的是服務端回復(response)被 處理后的版本,我們沒拿到服務器發回來原始的回復,我們怎么查看 服務器返回的HTTP 裸回復呢?
我們可以用HTTP工具 來實現,我們在地址欄輸入URL, 我們的HTTP工具會發送一個請求到 https://www.reddit.com.我們的HTTP 工具,Paw,不會處理服務端的回復(response),那原始回復的response 是什么樣呢?如下圖
What a huge difference this raw response is from the display in your browser! If you've never seen raw HTTP response data before, this may be quite shocking. What you see here is, in fact, what your browser also receives, except it parses and processes that huge blob of data into a user-friendly format.
If you're learning about HTTP in order to become a web developer, you'll need to learn to read and process raw HTTP response data just by scanning it. Of course, you won't be able to convert it into a high-resolution picture in your head, but you should have a general idea of what the response is about. With enough experience, you can dig into the raw data and do some debugging and see exactly what's in the response.
這個和在瀏覽器上顯示的有很大的區別! 你的瀏覽器也會受到一樣的裸回復(response)數據,瀏覽器可以對回復數據進行解析,并以一個友好的方式向用戶呈現出來。
如果你在學習HTTP ,目的是做一個web 開發者,你需要學習和讀懂如何處理這些裸數據(response).當然,你無法把response轉換為頭腦中一個高精度的照片,但是你應該大概了解這個回復是什么含義。只要有足夠的經驗,你就可以閱讀這些裸數據,并做一些調試工作,看看回復(response)是什么。
我在Postman 里面輸入地址后,打開console,也可以看到下面返回的裸回復。
Using the Inspector
Every modern browser has a way to view HTTP requests and responses, and it's usually called the inspector. We're going to use the Chrome Inspector to demonstrate how to analyze your browser's HTTP communication.
Launch Chrome browser and open the Inspector by navigating to the Chrome Menu on the top right-hand corner of your browser. Select Tools > More Tools > Developer Tools. There are other ways of accessing the inspector, such as right-clicking and selecting the 'Inspector' option, or using a keyboard shortcut Ctrl+Shift+I (or Option+Command+I on a Mac).
Send a new request to Reddit by entering the address https://www.reddit.com into your browser.
With the inspector still open click on the Network tab:
翻譯:
使用檢查員(inspector)
每一個現代的瀏覽器都有辦法可以讀HTTP 請求和回復請求,這個方式就是檢查員。我們將使用google 瀏覽器Chrome 的檢查員(inspector)來分析瀏覽器的HTTP通信。
國內訪問,果然時間要長很多。
4. The first thing you should notice is that there are a lot of entries there. Each entry is a separate request, which means just by visiting the URL,
your browser is making multiple requests, one for every resource (image, file, etc.). Click on the first request for the main page, www.reddit.com entry:
翻譯:
首先需要知道的是,這里很多的條目,每個條目是一個單獨的請求。這意味著(敲黑板),即使只是訪問url,你的瀏覽器已經做了多個request,針對每個資源會申請一次(資源包括圖片、文件等等)。鼠標點擊主頁條目看一下,www.reddit.com 條目:
From here, you'll be able to see the specific request headers, cookies as well as the raw response data:
翻譯:
這里可以看到針對這個主頁的請求,cookie 以及裸回復(response)。
The response data should look similar to what we saw earlier using our HTTP tool, except Chrome displays the data in a single line.
Another thing to note when using the inspector's Network tab is, other than the first request, there are a ton of other requests returned:
翻譯:
回復的數據應該和之前我們用HTTP 工具 看到的內容是相似的,區別是google 瀏覽器在單行中顯示數據。(這里在新版本google 瀏覽器已經改過來了)
另外一個需要關注的是,使用inspector network 這個表,除了看到第一個請求,還有非常多的其它請求返回。(如下圖)
Why are these additional responses sent back, who initiated the requests? What's happening is that the resource we requested, the initial www.reddit.com entry, returned some HTML. And in that HTML body are references to other resources like images, css stylesheets, javascript files and more. Your browser, being smart and helpful, understands that in order to produce a visually appealing presentation, it has to go and grab all these referenced resources. Hence, the browser will make separate requests for each resource referenced in the initial response. When you scroll down the Network tab, you'll be able to see all the referenced resources. These other requests are to make sure the page displays properly on your screen, among other things. Overall, you see that the browser's inspector gives you a good feel for these referenced resources. A pure HTTP tool, on the other hand, returns one huge response chunk without any concern for automatically pulling in referenced resources. A curl request will demonstrate this:
翻譯:
為什么會有額外的回復被發回來? 第一個請求條目,www.reddit.com 返回來一些HTML 的文件。這個文件指向了其它的資源,比如圖片、CSS、JS 文件。而你的瀏覽器足夠聰明和幫助,理解了這個HTML,并去抓去了所有相關的資源。
這樣,在最開始的回復后,瀏覽器會針對每個資源做單獨的申請。當你在network 表往下查看所有的表,你能夠看到所有被引用的資源。這些其它的請求可以幫助你把頁面在你的屏幕顯示的更加清晰,總的來看,瀏覽器inspector 給你一個好的感覺,針對所有的資源。
一個純HTTP 工具,只會返回一個巨大的response 片段,不會考慮自動的去把關聯到的資源拉群進來。一個curl 工具一般顯示的內容如下:
Reddit now requires that we add in a User-Agent to our HTTP requests. Otherwise, it will deny our request, assuming that the request originates from a bot.
Make sure to append the following to any curl commands where reddit is the site you wish to send a request to.
-A 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.101 Safari/537.36'
The -A option is used to specify a User-Agent for an HTTP request when using curl. Since this is another option for our command,
don't forget to add in a space between -v and -A.
For the sake of simplicity, we specify the User-Agent that is listed at the end of this page. You may use your own User-Agent as well.
$ curl -X GET "https://www.reddit.com/" -m 30 -v
What you should see is just one request and the response containing the HTML, but no additional requests being automatically issued, like you see in a browser.
翻譯:
下圖,curl 百度的效果圖:
Request Methods
Let's revisit the diagram from Step 3 above, when we looked at the responses in the Network tab. You might have noticed two columns named Method and Status.
If you don't see the Methodcolumn, it may be hidden by default. To display the Method column, right click on Status and select Method.
The Method column should now be visible next to the Status column.
翻譯:
請求方法
讓我們重新調到第三步(在google瀏覽器inspector那一步),我們在network 里面查看responses的時候,你可以看到兩列:method 和 status.在status 狀態上右鍵,選擇展示method,如下圖。
We'll spend this section looking at what the information shown in these columns mean.
Information displayed in the Method column is known as the HTTP Request Method. You can think of this as the verb that tells the server what action to perform on a resource. The two most common HTTP request methods you'll see are GET and POST. When you think about retrieving information, think GET, which is the most used HTTP request method. In the above diagram, you'll notice almost all of the requests use GET to retrieve the resources needed to display the web page.
The Status column shows the response status for each request. We'll talk about responses in detail later in the book. The important thing to understand is that every request gets a response, even if the response is an error -- that's still a response. (That's not 100% technically true as some requests can time out, but we'll set those rare cases aside for now.)
我們將花一點時間介紹下這些列里包含信息的含義。
當你想獲取信息,用GET 方法,這是最常用的HTTP 請求方法,在上面的請求中,你可以看到幾乎所有的請求都是GET .狀態列顯示 每個請求的返回狀態,我們在本書稍后會介紹狀態的含義。需要了解的是,每一個請求都會有一個回復(response),即使回復還是錯誤的,這仍然是一個回復。(當然有些超時的除外)
GET Requests
GET requests are initiated by clicking a link or via the address bar of a browser. When you type an address like https://www.reddit.com into the address bar of your browser, you're making a GETrequest. You're asking the web browser to go retrieve the resource at that address, which means we've been making GET requests throughout this book. The same goes for interacting with links on web applications. The default behavior of a link is to issue a GET request to a URL. Let's make a simple GET request to https://www.reddit.com with an HTTP tool. Make sure to select GET and enter the address:
You can view the raw HTTP response and other information sent back from the web server on the right panel.curl users can enter the following command on their terminal:
$ curl -X GET "https://www.reddit.com/" -m 30 -v
We can also send query strings using an HTTP tool. Let's look at another quick example by sending a request to search for all things Michael Jackson at https://itunes.apple.com/ with query strings. The final URL will look like this:
https://itunes.apple.com/search?term=Michael%20Jackson
before submitting a request, make sure to select GET.
Here we are simply sending an HTTP GET request to the server at https://itunes.apple.com/ with parameter term=Michael%20Jackson where %20 is a URL-encoded character for SPACE.
The curl command for this example is:
$ curl -X GET "https://itunes.apple.com/search?term=Michael%20Jackson" -m 30 -v
That's all you need to know about issuing HTTP GET requests for now. The primary concepts are:
翻譯
你需要了解的是:
POST Requests
We've seen how to retrieve or ask for information from a server with GET, but what if you need to send or submit data to the server? That's where another essential HTTP request method comes in: POST. POST is used when you want to initiate some action on the server, or send data to a server. Let's see an example with our HTTP tool:
翻譯:
如果需要提交信息到服務器,這個時候需要使用HTTP 請求的另外一個方法,POST。 當你需要對服務器發起某些操作,或者發送數據到服務器,需要POST。
Here is the curl command:
$ curl -X POST "https://echo.epa.gov" -m 30 -v
The above screenshot shows a POST request to https://echo.epa.gov and the response from the server. Typically from within a browser, you use POST when submitting a form. POST requests allow us to send much larger and sensitive data to the server, such as images or videos. For example, say we need to send our username and password to the server for authentication. We could use a GET request and send it through query strings. The flaw with this approach is obvious: our credentials become exposed instantly in the URL; that isn't what we want. Using a POST request in a form fixes this problem. POST requests also help sidestep the query string size limitation that you have with GET requests. With POST requests, we can send significantly larger forms of information to the server.
Let's see another example of making a POST request by filling out a web form. Our sample form looks like this in the browser:
翻譯:
curl 命令行如下:
$ curl -X POST "https://echo.epa.gov" -m 30 -v
After filling out the form, you'll be redirected to a page that looks like this:
Now let's switch over to our HTTP tool and simulate what we just did in the browser. Instead of filling out a form in the browser, we will send a POST request to http://al-blackjack.herokuapp.com/new_player. This is the URL that the first form (the one where we input a name) submits to:
翻譯:
我們換到HTTP 工具上來模擬我們在瀏覽器上的操作,代替我們在瀏覽器上填入信息,我們會發送Post 請求到 http://al-blackjack.herokuapp.com/new_player
我們第一個表格(我們輸入名字的)提交到這個url:
Note: You'll want to ensure that your Content-Type header is set to application/x-www-form-urlencoded. If it isn't, then your POST request won't be interpreted by the application correctly.
If you're using Paw 3, select the Form URL-Encoded tab instead of the Text tab.
If you're using Insomnia, make sure you click "Form URL Encoded" in the Body dropdown menu. And if you're using Postman, make sure the radio button for x-www-form-urlencodedis selected under the Body tab.
翻譯:
你會希望保證你的 content-type header 為 application/x-www-form-urlencoded.如果不這樣設置,服務器將無法識別請求。
如果選擇postman,記得選擇了 x-www-form-urlencode 按鈕,在body表中。
譯者在postman中的操作截圖:
303 see other的含義:(from 譯者)
Or you can use curl:
$ curl -X POST "http://al-blackjack.herokuapp.com/new_player" -d "player_name=Albert" -m 30 -v
Notice that in the screenshot and curl command we're supplying the additional parameter of player_name=albert. It has the same effect as inputting the name into the first "What's your name?" form and submitting it.
We can verify the contents using the inspector (right click and select Inspect). You'll see that the player_name parameter we're sending as part of the POST request is embedded in the form via the nameattribute of the input element:
翻譯:
或者你可以用curl 命令實現 :
$ curl -X POST "http://al-blackjack.herokuapp.com/new_player" -d "player_name=Albert" -m 30 -v
這里 -d "player_name=Albert" 和在瀏覽器里面填入 “what's your name?”表格效果是一樣的,可以在瀏覽器里面看到, player_name 參數是保存在表格里的。
But the mystery is, how is the data we're sending being submitted to the server since it's no
t being sent through the URL? The answer to that is the HTTP body.
The body contains the data that is being transmitted in an HTTP message and is optional. In other words, an HTTP message can be sent with an empty body.
When used, the body can contain HTML, images, audio and so on. You can think of the body as the letter enclosed in an envelope, to be posted.
The POST request generated by the HTTP tool or curl is the same as you filling out the form in the browser, submitting that form, and then being redirected to the next page.
Look carefully at the raw response in the HTTP tool screenshot. The key piece of information that redirects us to the next page is specified in the field Location:
http://al-blackjack.herokuapp.com/bet. Location and its associated data is part of what is known as an HTTP response header (yes, requests have headers too, but in this case,
it's a response header). Don't worry too much about this yet as we'll discuss headers in a later section. Your browser sees the response header and automatically issues a brand
new request to the URL specified in the Location header, thereby initiating a new, unrelated request. The "Make a bet" form you see is the response from that second request.
翻譯:
不過疑問就在,這個數據是怎么提交到服務器上的,因為他沒有通過URL 提交。
答案是:HTTP body (HTTP 身體)(敲黑板),HTTP body包含了傳遞給HTTP的數據,這個是可選的。
http://al-blackjack.herokuapp.com/bet. ( request 請求有Header ,這里是response 的header信息)你的瀏覽器看到了response header, 自動發起了一個新的請求到url (location 字段里指定的),這樣就看到了第二個response 表格。
Note: If you're using some other HTTP tool, like Insomnia or Postman, you may have to uncheck "automatically follow redirects" in order to see the Location response header.
If you're fuzzy on the previous paragraph, read it again. It's critical to understand that when using a browser, the browser hides a lot of the underlying HTTP request/response cycle from you. Your browser issued the initial POST request, got a response with a Location header, then issued another request without any action from you, then displayed the response from that second request. Once again, if you were using a pure HTTP tool, you'd see the Location response header from the first POST request, but the tool would not automatically issue a second request for you. (Some HTTP tools have this ability, if you check the "automatically follow redirects" option.)
翻譯:
這里就是對上文的重復解釋,不復述了。
HTTP Headers
HTTP headers allow the client and the server to send additional information during the request/response HTTP cycle. Headers are colon-separated name-value pairs that are sent in plain text. By using the Inspector, we can see these Headers. Below, you can see both the request as well as the response headers:
The above shows the various headers being transmitted during a request/response cycle. Further, we can see that the request and response contain a different set of headers under Request Headers:
The above shows the various headers being transmitted during a request/response cycle.
Further, we can see that the request and response contain a different set of headers under Request Headers:
Request Headers
Request headers give more information about the client and the resource to be fetched. Some useful request headers are:
Don't bother memorizing any of the request headers, but just know that it's part of the request being sent to the server. We'll talk about response headers in the next chapter.
翻譯:
這里講了request header 的一些信息,request header 和 response header 信息是不一樣的。
上圖里request header 里面包含有:主機名、接受的語言、用戶端agent 信息、連接信息。
Summary
This was a brief introduction on making HTTP requests. After going through this section, you should be comfortable with:
In the next chapter, we'll continue learning about HTTP by looking at HTTP responses.
翻譯:
本章節介紹了下HTTP requests 信息,
經過本章節,你可以:
使用inspector 來 查看HTTP requests 請求
使用HTTP 工具來發起GET /POST 請求
最需要了解的組件包括:
HTTP 方法
路徑
headers 頭部
消息體(針對post 請求)
*請認真填寫需求信息,我們會在24小時內與您取得聯系。