简单测试get和post请求

本文的目的是记录学习http过程遇到的问题,因此使用tomcat搭建了服务器,简单测试get和post,本篇只是简单记录并不深入探究get和post的差异,需要更详细的可以看这篇https://www.jianshu.com/p/78b7012e27b3

1.安装tomcat与eclipse 。
这部分可以参考我这篇文章。
tomcat+eclipse+servlet在chrome上实现 https 双向认证简单记录
2.新建工程。
点击菜单栏File->New->Dynamic Web Project

image.png

随意命名xxx,点击finish。
image.png

然后,选中刚刚新建的项目xxxx,右键选择New->Servlet。
image.png

在Class name中填xxxx,然后点击finish。
image.png

于是自动生成如下文件。
image.png

代码具体如下。



import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Test
 */
@WebServlet("/Test")
public class Test extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Test() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

接下来将doPost()函数中的代码修改一点。

 doGet(request, response);

改为

response.getWriter().append("Served1111 at: ").append(request.getContextPath());

这样在后续使用postman测试的get和post时候返回的数据就不一样了。

改好后保存,然后选中java文件后右键,选择run as ,然后点击run on server。

image.png

点击finish。
image.png

自动访问下面的链接。
http://localhost:8080/Tttt/Test
response如下所示,这里是get。
image.png

3.postman简单使用
浏览器中只能测试get,无法测试post。早几年windows中可以使用firefox中的poster或者chrome中的postman插件,但是现在不行了。
不过postman还能用,但是需要下载客户端。
下载地址:
https://www.getpostman.com/downloads/
下载好所需版本后,需要注册账号。
注册号账号后进入客户端,主界面如下。这里不需要创建,直接x掉。

image.png

使用untitled request
image.png

先测试get。
方法选择get,然后填上链接 http://localhost:8080/Tttt/Test,最后点击send。

image.png

结果如下。


image.png

image.png

将get改成post后再次send。


image.png

image.png

至此,pc端的get和post的简单测试就完成了。
如果想使用android真机测试的话,在保证手机和电脑在同一局域网的情况下使用pc端的ip地址去替换localhost。
在cmd窗口中输入ipconfig,找到ipv4地址。

然后android端可访问链接即为 http://xx.xx.xx.xx:8080/Tttt/Test (xx部分为本机ip地址)。

android端测试代码比较简单,简单贴一下:
首先在manifest中添加网络权限。

    <uses-permission android:name="android.permission.INTERNET"/>

Activity文件如下。


public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private Button bt_get;
    private Button bt_post;
    //url需替换成自己的android端可访问的链接
    private String url = "http://10.4.17.27:8080/Tttt/Test";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bt_get = (Button) findViewById(R.id.bt_get);
        bt_get.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            URL httpUrl = new URL(url);
                            HttpURLConnection con=(HttpURLConnection) httpUrl.openConnection();
                            InputStream inputStrea = null;//字节流
                            inputStrea = con.getInputStream();
                            InputStreamReader inputStreamReader = new InputStreamReader(inputStrea);//转为字符流
                            //通过bufferReader 读取
                            BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
                            String content = null;
                            content = bufferedReader.readLine();
                            int responseCode = 0;//获得状态码
                            responseCode = con.getResponseCode();
                            String headerField=con.getHeaderField("Server");//获取消息头 名字为 Server的头
                            Log.d(TAG,"content = " + content);
                            Log.d(TAG, "responseCode = " + responseCode );
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });

        bt_post = (Button) findViewById(R.id.bt_post);
        bt_post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            URL httpUrl = new URL(url);
                            HttpURLConnection con=(HttpURLConnection) httpUrl.openConnection();
                            con.setDoOutput(true);//cannot write to a URLConnection if doOutput=false - call setDoOutput(true)
                            //给服务器发送请求头
                            con.setRequestMethod("POST");
                            con.getResponseCode();//表示 请求完成  一个请求是有来回的

                            InputStream inputStrea = null;//字节流
                            inputStrea = con.getInputStream();
                            InputStreamReader inputStreamReader = new InputStreamReader(inputStrea);//转为字符流
                            //通过bufferReader 读取
                            BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
                            String content = null;
                            content = bufferedReader.readLine();
                            int responseCode = 0;//获得状态码
                            responseCode = con.getResponseCode();
                            String headerField=con.getHeaderField("Server");//获取消息头 名字为 Server的头
                            Log.d(TAG,"content = " + content);
                            Log.d(TAG, "responseCode = " + responseCode );
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
    }

}

xml文件如下。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/bt_get"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="get"/>

    <Button
        android:id="@+id/bt_post"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="post"/>

</LinearLayout>

run后分别点击get和post后结果如下。


image.png
09-16 16:00:50.822 28865-30737/? D/MainActivity: content = Served at: /Tttt
09-16 16:00:50.822 28865-30737/? D/MainActivity: responseCode = 200
09-16 16:00:52.274 28865-30746/? D/MainActivity: content = Served1111 at: /Tttt
09-16 16:00:52.274 28865-30746/? D/MainActivity: responseCode = 200

这篇文章到此就结束了,下面接着回到http的学习中去。

参考链接:
Postman安装与使用

手机访问本地Tomcat服务器
https://www.jianshu.com/p/de48dc7981fe

Java HttpURLConnection 小demo
https://www.jianshu.com/p/863b1f2c4c74

GET与POST请求详解
https://www.jianshu.com/p/78b7012e27b3

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,110评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,443评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,474评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,881评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,902评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,698评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,418评论 3 419
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,332评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,796评论 1 316
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,968评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,110评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,792评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,455评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,003评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,130评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,348评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,047评论 2 355

推荐阅读更多精彩内容