您的位置:首页 > 编程语言 > Java开发

java代码分别发送get和post请求。

2018-01-21 22:18 507 查看
/**
* 发送get请求
*/
public static String sendGet(String url,String param){
String result="";
try {
url += "?"+param;
URL urlObj = new URL(url);
URLConnection connection = urlObj.openConnection();
connection.setRequestProperty("accept", "text/html");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");
connection.connect();

Map<String, List<String>> map = connection.getHeaderFields();
for(String key:map.keySet()){
System.out.println(key+"---"+map.get(key));
}

// 定义输入流来读取URL的内容
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
String line;
while((line = bufferedReader.readLine())!=null){
result += "\r\n" + line;
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 发送post请求
*/
public static String sendPost(String url,String param){
String result="";
try {
URL urlObj = new URL(url);
URLConnection connection = urlObj.openConnection();
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");
connection.setDoOutput(true);
connection.setDoInput(true);

PrintWriter printWriter = new PrintWriter(connection.getOutputStream());
printWriter.print(param);
printWriter.flush();

// 定义输入流来读取URL的内容
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
String line;
while((line = bufferedReader.readLine())!=null){
result += "\r\n" + line;
}

} catch (Exception e) {
e.printStackTrace();
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息