天天看点

java发送get请求_java发送http的get、post请求

public static String sendGet(String url, String param) {

String result = "";

BufferedReader in = null;

try {

String urlNameString = url + "?" + param;

URL realUrl = new URL(urlNameString);

URLConnection connection = realUrl.openConnection();// 打开和URL之间的连接

connection.setRequestProperty("accept", "*

public static String sendPost(String url, String param) {

PrintWriter out = null;

BufferedReader in = null;

String result = "";

try {

URL realUrl = new URL(url);

URLConnection conn = realUrl.openConnection();

conn.setRequestProperty("accept", "*/*");

conn.setRequestProperty("connection", "Keep-Alive");

conn.setRequestProperty("user-agent",

"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

conn.setDoOutput(true);

conn.setDoInput(true);

out = new PrintWriter(conn.getOutputStream());

out.print(param);xn--%20-8u3esc473lftkkz5d4uh

out.flush();xn--%20flush-hz6mgxn41v6hxa2vyrg5c

in = new BufferedReader(// 定义BufferedReader输入流来读取URL的响应

new InputStreamReader(conn.getInputStream()));

String line;

while ((line = in.readLine()) != null) {

result += line;

}

} catch (Exception e) {

System.out.println("发送 POST 请求出现异常!"+e);

e.printStackTrace();

}

//使用finally块来关闭输出流、输入流

finally{

try{

if(out!=null){

out.close();

}

if(in!=null){

in.close();

}

}

catch(IOException ex){

ex.printStackTrace();

}

}

return result;

}

}

public static void main(String[] args) {

//发送 GET 请求

String s=HttpRequest.sendGet("http://localhost:6144/Home/RequestString", "key=123&v=456");

System.out.println(s);

//发送 POST 请求

String sr=HttpRequest.sendPost("http://localhost:6144/Home/RequestPostString", "key=123&v=456");

System.out.println(sr);

}