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小时内与您取得联系。