一个简单的HTTP通信,GET&POST方式,调接口

socket通信

https://blog.csdn.net/qq_40726316/article/details/96442103

socket和url的区别?

socket只需给个ip,给个端口,然后服务器端给个端口号 ,就可以进行通信。

而url需要ip,端口,具体的项目接口url,对应需要传递的参数。

这是我的理解。可以参考一下别人的理解。

https://blog.csdn.net/grey_mouse/article/details/84578837

Get与POST请求?

Get请求:不安全,参数直接在url。

Post请求:安全,url中看不见对应的参数。

https://blog.csdn.net/hemingyang97/article/details/82053961

跨项目调用接口,怎么调用?

项目没有放在同一个服务器上,需要访问时,只能通过url访问,通过url访问,数据就要以报文格式传输。调用接口,就要有接口的唯一路径,以及要传递的参数。

//get形式的请求url
url = new URL("http://localhost:8080/practiceinterface_war_exploded/customerService2?id='11111'");

//post形式的请求url
//请求参数格式
String canshu="id=1835172627&name=周亚娟";
//请求url
URL url=new URL("http://localhost:8080/practiceinterface_war_exploded/customerService2");


//建立连接
URLConnection connection= (URLConnection) url.openConnection();
//设置post请求的必须请求头
connection.setRequestProperty("accept","*/*");
connection.setRequestProperty("Connection","Keep-Alive");
connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

 //post请求必须设置
 connection.setDoInput(true);
 connection.setDoOutput(true);

 //获取连接输出流
 OutputStream os=connection.getOutputStream();
 //把输出流转成打印流
 PrintWriter out=new PrintWriter(os);
 //发送请求参数
 out.print(canshu);
 //刷新缓存
 out.flush();

作为接口端如何把响应数据传出去?

        //设置响应编码格式,防止乱码
        req.setCharacterEncoding("UTF-8");
        selectCustomerInfo selectCustomerInfo1=new selectCustomerInfo();
        Customer customer=selectCustomerInfo1.findCustomerByCustomer(req.getParameter("id"),req.getParameter("name"));
        
        //设置响应编码格式,防止乱码
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().write(customer.getId());
        resp.getWriter().write("post报文");
        resp.getWriter().write(customer.getName());

 接口端通过

HttpServletResponse.getWriter().write("需要传递出去的内容");

来把数据传递出去。

客户端通过

connection.getInputStream()来获取接口端传递过来的内容

然后通过

String result="";
BufferedReader in = null;
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
        new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
    result += line;
}
System.out.println(result);

把数据打印出来。

作为客户端如何把请求参数传出去?

get方式直接通过url键值对的方式传递。post方式通过参数写入的方式写入到输出流,进行传递。


项目源码:

客户端:

package com.practice.httptest;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;

public class PostHttp {
    public static void main(String[] args) {
        try {
            String canshu="id=1835172627&name=周亚娟";//参数格式=========>"key=123&v=456"
            URL url=new URL("http://localhost:8080/practiceinterface_war_exploded/customerService2");
            PrintWriter out = null;
            URLConnection connection= (URLConnection) url.openConnection();

            //post请求报文格式??????
            //

//            POST:
//            POST报文头如下:
//
//            POST /sn/index.php HTTP/1.1
//            Accept: */*
//            Accept-Language: zh-cn
//            host: localhost
//
//
//            Content-Type: application/x-www-form-urlencoded
//            Content-Length: 12
//            Connection:close
//            sn=123&n=asa
//            在http头后边有一空行,空行后边接着发送post数据,长度通过Content-Length: 12
//            指出,此post数据中包含两项
//            sn=123
//            n=asa
//            其中:Content-Type: application/x-www-form-urlencoded 指定POST数据的编码类型
//            Content-Length: 12 POST数据的长度



            //post请求头必须
//            Accept: */*
//            Connection:Keep-Alive
//            user-agent:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)

            connection.setRequestProperty("accept","*/*");
            connection.setRequestProperty("Connection","Keep-Alive");
            connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            //post请求必须设置
            connection.setDoInput(true);
            connection.setDoOutput(true);

            //获取连接输出流
            OutputStream os=connection.getOutputStream();
            //把输出流转成打印流
            out=new PrintWriter(os);
            //发送请求参数
            out.print(canshu);
            //刷新缓存
            out.flush();
            String result="";
            BufferedReader in = null;
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            System.out.println(result);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

服务端:

package com.prainter.servlet;
import com.prainter.example.Customer;
import com.prainter.example.selectCustomerInfo;

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

public class customerServlet1 extends HttpServlet{
    //socket通信?输入输出流?Get与POST请求?跨项目调用接口,怎么调用?作为接口端如何把响应数据传出去?作为客户端如何把请求参数传出去?socket和url 的区别?
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("进的是get请求");
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //设置响应编码格式,防止乱码
        req.setCharacterEncoding("UTF-8");
        selectCustomerInfo selectCustomerInfo1=new selectCustomerInfo();
        Customer customer=selectCustomerInfo1.findCustomerByCustomer(req.getParameter("id"),req.getParameter("name"));

        //设置响应编码格式,防止乱码
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().write(customer.getId());
        resp.getWriter().write("post报文");
        resp.getWriter().write(customer.getName());
        //req.getRequestDispatcher("/index.jsp").forward(req,resp);

        //resp.sendRedirect("/index.jsp");
        //super.doPost(req, resp);
    }
}
package com.prainter.example;

public class selectCustomerInfo {
    public int findCustomerByCustomer(String id,int age){
        return 1;
    }


    public Customer findCustomerByCustomer( String id,String name){
        Customer customer=new Customer(id,name);
        return customer;
    }



}
package com.prainter.example;

public class Customer {
    private String id;
    private String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Customer(String id,String name) {
        this.id = id;
        this.name=name;
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>servlet1</servlet-name>
        <servlet-class>com.prainter.servlet.customerServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>servlet1</servlet-name>
        <url-pattern>/customerService</url-pattern>
    </servlet-mapping>


    <servlet>
        <servlet-name>servlet2</servlet-name>
        <servlet-class>com.prainter.servlet.customerServlet1</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>servlet2</servlet-name>
        <url-pattern>/customerService2</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
发布了56 篇原创文章 · 获赞 18 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_40726316/article/details/96483333