欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java发送get请求和post请求示例

程序员文章站 2024-02-24 14:02:04
java向服务端发送get和post请求 复制代码 代码如下:package com.hongyuan.test; import java.io.bufferedrea...

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);
 }

}