java发送get请求和post请求示例
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);
}
}
上一篇: mysql之set与enum的介绍