我们将使用java.net.URLConnection来完成一次post请求,假设要post数据到http://localhost:8080/doSome上:
URLConnection urlConn = new URL("http://localhost:8080/doSome").openConnection(); //设置http method为post方式
urlConn.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(urlConn.getOutputStream()); //请求参数,注意格式
String params = "status=on&name=john"; //然后进行一下url编码
params = URLEncoder.encode(params); //写入请求参数
try {
out.write(params);
} catch(IOException e) {
throw new IOException("something bad happend" , e);
} finally {
out.close();
}
如果使用get方式请求的话,那直接使用
URLConnection urlConn = new URL("http://localhost:8080/doSome").openConnection();
即可,因为其默认为get请求方式,若要附加参数的话,可直接附加在url上,如
URLConnection urlConn = new URL("http://localhost:8080/doSome?stauts=on&name=john").openConnection();