1. 程式人生 > >Java POST請求案例

Java POST請求案例

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<直接上程式碼>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Person(物件)

public class Person {
    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

PersonReq(請求引數物件)

public class PersonReq {
    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

DemoService(業務類)

package com.demo;

import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class DemoService {
    /**
     * 獲取列表
     *
     * @param personReq 物件引數
     * @return
     */
    public List<Person> personList(PersonReq personReq) {
        List<Person> list = new ArrayList<>();
        Person person = new Person();
        person.setAge(personReq.getAge());
        person.setName(personReq.getName());
        Person person1 = new Person();
        person1.setAge(20);
        person1.setName("2詩");
        list.add(person);
        list.add(person1);
        return list;
    }
}

DemoController(控制類)

package com.demo;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/demo")
public class DemoController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    DemoService demo;

    @PostMapping("/list")
    public List<Person> getPerson(@RequestBody PersonReq personReq) {
        List<Person> people = demo.personList(personReq);
        logger.info("list:{}", JSON.toJSONString(people));
        return people;
    }
}

Application (啟動類)

啟動專案,然後下一步,外部 就可以開始調介面了

package com;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@EnableScheduling
@EnableSwagger2
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

HttpClients(工具類)

package com.demo;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * HTTP 工具類
 */
public class HttpClients {
    /**
     * 傳送POST請求
     *
     * @param url   請求URL
     * @param param 請求引數
     * @return
     */
    private String sendPost(String url, String param) {


        return null;
    }

    public static String sendPost(String url, String request, String ContentType) {
        String result = "";

        try {
            //儲存請求
            PrintWriter out;

            //儲存介面返回的response
            BufferedReader in;

            // 獲取訪問地址
            //得到網路訪問物件java.net.HttpURLConnection
            URL realUrl = new URL(url);

            //設定請求引數,以流的形式連線
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();

            //設定http的請求頭
            conn.setRequestProperty("accept", "*/*");

            //設定請求的Contenttype
            if (ContentType == null || ContentType.equals("")) {
                if (isJson(request)) {
                    conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
                } else {
                    if (url.toLowerCase().contains(".asmx")) {
                        conn.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
                    } else {
                        conn.setRequestProperty("Content-Type", "application/xml;charset=utf-8");
                    }
                }
            } else {
                conn.setRequestProperty("Content-Type", ContentType);
            }

            //特殊處理:如果是1.0的請求則進一步具體設定setRequestProperty,並對xml格式做優化
            if (url.toLowerCase().contains(".asmx")) {
                if (url.toLowerCase().contains("datacomparews")) {
                    conn.setRequestProperty("SOAPAction", "http://tempuri.org/DataTableCompare");
                    String Xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                            "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                            "<soap:Body>";
                    Xml += request.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
                    Xml += "</soap:Body></soap:Envelope>";
                    request = Xml;
                } else {
                    String Xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                            "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                            "<soap:Body><Request xmlns=\"http://tempuri.org/\"><requestXML>" + "<![CDATA[";
                    Xml += request.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
                    Xml += "]]></requestXML></Request></soap:Body></soap:Envelope>";
                    request = Xml;
                    conn.setRequestProperty("SOAPAction", "http://tempuri.org/Request");
                }
            }

            //keep-alive 發出的請求建議伺服器端保留連線,這樣下次向同一個伺服器發請求時可以走同一個連線
            conn.setRequestProperty("connection", "Keep-Alive");

            //設定請求的瀏覽器相關屬性
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            //設定接受的返回流位元組碼為UTF-8
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("Charset", "utf-8");

            //設定超時時間,如果未設定超時時間,但是訪問超時了就會一直卡在這裡
            conn.setConnectTimeout(50000 * 12);
            conn.setReadTimeout(50000 * 12);

            //設定是否向HttpURLConnection輸出,預設為false,傳送post請求的不啊必須設定為true
            conn.setDoOutput(true);

            //設定是否從httpUrlConnection讀入,預設為true,不設定也可以
            conn.setDoInput(true);

            //處理輸入請求 ,設定請求正文,即要提交的資料
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));

            // 寫入引數到請求中
            out.print(request);

            //flush輸出流的緩衝
            out.flush();

            //處理輸出介面,遠端物件變為可用
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));

            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            result = e.getMessage();
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 判斷字串是不是json格式
     *
     * @param request
     * @return
     */
    private static boolean isJson(String request) {
        try {
            JSONObject.parseObject(request);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}

Demo1Controller(外部呼叫類)

package com.demo;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/demo1")
public class Demo1Controller {
    private static final Logger logger = LoggerFactory.getLogger(Demo1Controller.class);

    @PostMapping("/list")
    public String getPerson1() {
        PersonReq personReq = new PersonReq();
        personReq.setAge(10);
        personReq.setName("1詩");
        String url = "http://localhost:8080/demo/list";
        String result = HttpClients.sendPost(url, JSON.toJSONString(personReq), "");
        logger.info(" getPerson1 list:{}", result);
        return result;
    }

//mian方法測試 public static void main(String[] args) { PersonReq personReq = new PersonReq(); personReq.setAge(10); personReq.setName("1詩"); String url = "http://localhost:8080/demo/list"; String result = HttpClients.sendPost(url, JSON.toJSONString(personReq), ""); logger.info("result:{}", result); } }

 

 <<<<<<<<<<<<<<<OK>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>