資源簡介
java調用HTTP接口(Get請求和Post請求)
代碼片段和文件信息
package?com.company;
import?java.io.*;
import?java.net.HttpURLConnection;
import?java.net.URL;
/**
?*?功能簡述:
?*
?*?@author?caidingnu
?*?@create?2019/03/27?13:46
?*?@since?1.0.0
?*/
public?class?HTTP_Request?{
????private?static?void?httpURLGETCase()?{
????????String?methodUrl?=?“http://127.0.0.1:8099/select_by_id?userid=1“;
????????HttpURLConnection?connection?=?null;
????????BufferedReader?reader?=?null;
????????String?line?=?null;
????????try?{
????????????URL?url?=?new?URL(methodUrl);
????????????connection?=?(HttpURLConnection)?url.openConnection();//?根據URL生成HttpURLConnection
????????????connection.setRequestMethod(“GET“);//?默認GET請求
????????????connection.connect();//?建立TCP連接
????????????if?(connection.getResponseCode()?==?HttpURLConnection.HTTP_OK)?{
????????????????reader?=?new?BufferedReader(new?InputStreamReader(connection.getInputStream()?“UTF-8“));//?發送http請求
????????????????StringBuilder?result?=?new?StringBuilder();
????????????????//?循環讀取流
????????????????while?((line?=?reader.readLine())?!=?null)?{
????????????????????result.append(line).append(System.getProperty(“line.separator“));//?“\n“
????????????????}
????????????????System.out.println(result.toString());
????????????}
????????}?catch?(IOException?e)?{
????????????e.printStackTrace();
????????}?finally?{
????????????try?{
????????????????reader.close();
????????????}?catch?(IOException?e)?{
????????????????e.printStackTrace();
????????????}
????????????connection.disconnect();
????????}
????}
//Post請求
private?static?void?httpURLPOSTCase()?{
????String?methodUrl?=?“http://127.0.0.1:8099/select_by_id?userid=1“;
????HttpURLConnection?connection?=?null;
????OutputStream?dataout?=?null;
????BufferedReader?reader?=?null;
????String?line?=?null;
????try?{
????????URL?url?=?new?URL(methodUrl);
????????connection?=?(HttpURLConnection)?url.openConnection();//?根據URL生成HttpURLConnection
????????connection
- 上一篇:鬧鐘java源碼
- 下一篇:java 多個實習報告
評論
共有 條評論