国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java發送get請求和post請求示例

2019-11-26 15:36:08
字體:
來源:轉載
供稿:網友

java向服務端發送GET和POST請求

復制代碼 代碼如下:

package com.hongyuan.test;

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

public class HttpClient {
 //發送一個GET請求
 public static String get(String path) throws Exception{
  HttpURLConnection httpConn=null;
  BufferedReader in=null;
  try {
   URL url=new URL(path);
   httpConn=(HttpURLConnection)url.openConnection();

   //讀取響應
   if(httpConn.getResponseCode()==HttpURLConnection.HTTP_OK){
    StringBuffer content=new StringBuffer();
    String tempStr="";
    in=new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
    while((tempStr=in.readLine())!=null){
     content.append(tempStr);
    }
    return content.toString();
   }else{
    throw new Exception("請求出現了問題!");
   }
  } catch (IOException e) {
   e.printStackTrace();
  }finally{
   in.close();
   httpConn.disconnect();
  }
  return null;
 }
 //發送一個GET請求,參數形式key1=value1&key2=value2...
 public static String post(String path,String params) throws Exception{
  HttpURLConnection httpConn=null;
  BufferedReader in=null;
  PrintWriter out=null;
  try {
   URL url=new URL(path);
   httpConn=(HttpURLConnection)url.openConnection();
   httpConn.setRequestMethod("POST");
   httpConn.setDoInput(true);
   httpConn.setDoOutput(true);

   //發送post請求參數
   out=new PrintWriter(httpConn.getOutputStream());
   out.println(params);
   out.flush();

   //讀取響應
   if(httpConn.getResponseCode()==HttpURLConnection.HTTP_OK){
    StringBuffer content=new StringBuffer();
    String tempStr="";
    in=new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
    while((tempStr=in.readLine())!=null){
     content.append(tempStr);
    }
    return content.toString();
   }else{
    throw new Exception("請求出現了問題!");
   }
  } catch (IOException e) {
   e.printStackTrace();
  }finally{
   in.close();
   out.close();
   httpConn.disconnect();
  }
  return null;
 }

 public static void main(String[] args) throws Exception {
  //String resMessage=HttpClient.get("http://localhost:3000/hello?hello=hello get");
  String resMessage=HttpClient.post("http://localhost:3000/hello", "hello=hello post");
  System.out.println(resMessage);
 }

}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: SHOW| 宝应县| 九龙城区| 郧西县| 临朐县| 金门县| 离岛区| 娄烦县| 河源市| 遂平县| 同德县| 砀山县| 华亭县| 敦化市| 绥中县| 清新县| 新建县| 宣城市| 大邑县| 青龙| 资兴市| 勐海县| 西昌市| 县级市| 镇康县| 隆安县| 桦南县| 鹤庆县| 健康| 安义县| 西林县| 岳普湖县| 农安县| 格尔木市| 开化县| 普陀区| 兴化市| 饶河县| 广德县| 平度市| 西充县|