读书人

运用Java发送GET、POST请求

发布时间: 2012-10-12 10:17:04 作者: rapoo

使用Java发送GET、POST请求
qaddRequestProperty(String key, String value):为该URLConnection的key请求头字段的增加value值,该方法并不会覆盖原请求头字段的值,而是将新值追加到原请求头字段中。
当远程资源可用之后,程序可以使用以下方法用于访问头字段和内容:

qObject getContent():获取该URLConnection的内容。
qString getHeaderField(String name):获取指定响应头字段的值。
qgetInputStream():返回该URLConnection对应的输入流,用于获取URLConnection响应的内容。
qgetOutputStream():返回该URLConnection对应的输出流,用于向URLConnection发送请求参数。
注意:如果既要使用输入流读取URLConnection响应的内容,也要使用输出流发送请求参数,一定要先使用输出流,再使用输入流。
getHeaderField方法用于根据响应头字段来返回对应的值。而某些头字段由于经常需要访问,所以Java提供了以下方法来访问特定响应头字段的值:
qgetContentEncoding:获取content-encoding响应头字段的值。
qgetContentLength:获取content-length响应头字段的值。
qgetContentType:获取content-type响应头字段的值。
qgetDate():获取date响应头字段的值。
qgetExpiration():获取expires响应头字段的值。
qgetLastModified():获取last-modified响应头字段的值。
下面程序示范了如何向Web站点发送GET请求、POST请求,并从Web站点取得响应的示例。

/**
?* @author TONY
?*
?*/
public class TestGetPost {
??? /**
??? ?* 向指定URL发送GET方法的请求
??? ?*
??? ?* @param url
??? ?*??????????? 发送请求的URL
??? ?* @param param
??? ?*??????????? 请求参数,请求参数应该是name1=value1&name2=value2的形式。
??? ?* @return URL所代表远程资源的响应
??? ?*/
??? public String sendGet(String url, String param) {
??? ??? String result = "";
??? ??? BufferedReader in = null;
??? ??? try {
??? ??? ??? String urlName = url + "?" + param;
??? ??? ??? URL realUrl = new URL(urlName);
??? ??? ??? // 打开和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.connect();
??? ??? ??? // 获取所有响应头字段
??? ??? ??? Map<String, List<String>> map = conn.getHeaderFields();
??? ??? ??? // 遍历所有的响应头字段
??? ??? ??? for (String key : map.keySet()) {
??? ??? ??? ??? System.out.println(key + "--->" + map.get(key));
??? ??? ??? }
??? ??? ??? // 定义BufferedReader输入流来读取URL的响应
??? ??? ??? in = new BufferedReader(
??? ??? ??? ??? ??? new InputStreamReader(conn.getInputStream()));
??? ??? ??? String line;
??? ??? ??? while ((line = in.readLine()) != null) {
??? ??? ??? ??? result += "\n" + line;
??? ??? ??? }
??? ??? } catch (Exception e) {
??? ??? ??? System.out.println("发送GET请求出现异常!" + e);
??? ??? ??? e.printStackTrace();
??? ??? }
??? ??? // 使用finally块来关闭输入流
??? ??? finally {
??? ??? ??? try {
??? ??? ??? ??? if (in != null) {
??? ??? ??? ??? ??? in.close();
??? ??? ??? ??? }
??? ??? ??? } catch (IOException ex) {
??? ??? ??? ??? ex.printStackTrace();
??? ??? ??? }
??? ??? }
??? ??? return result;
??? }

??? /**
??? ?* 向指定URL发送POST方法的请求
??? ?*
??? ?* @param url
??? ?*??????????? 发送请求的URL
??? ?* @param param
??? ?*??????????? 请求参数,请求参数应该是name1=value1&name2=value2的形式。
??? ?* @return URL所代表远程资源的响应
??? ?*/
??? public String sendPost(String url,String param) {???
??? ??? String result = "";
??? ??? String urlName = url+"?"+param;??? ???
??? ???
??? ??? URL realUrl;
??? ??? try {
??? ??? ??? realUrl = new URL(urlName);??? ???
??? ??? ??? URLConnection conn;
??? ???
??? ??? ??? conn = realUrl.openConnection();
??? ???
??? ???
??? ??? ??? conn.setDoInput(true);
??? ??? ??? conn.setDoOutput(true);
??? ??? ??? 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.connect();
??? ??? ???
??? ??? ??? OutputStream out = conn.getOutputStream();
??? ??? ??? out.write("".getBytes());
??? ??? ??? out.flush();
??? ??? ??? out.close();
??? ??? ??? ??? ???
??? ??? ??? BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
??? ??? ??? String line = "";
??? ??? ??? while ((line = reader.readLine())!= null){
??? ??? ??? ??? result += "\n" + line;
??? ??? ??? }
??? ???
??? ??? } catch (MalformedURLException e) {
??? ??? ??? // TODO Auto-generated catch block
??? ??? ??? e.printStackTrace();
??? ??? } catch (IOException e) {
??? ??? ??? // TODO Auto-generated catch block
??? ??? ??? e.printStackTrace();
??? ??? }
??? ??? return result;
??? }

// 提供主方法,测试发送GET请求和POST请求
??? public static void main(String args[]) {
??? ??? // 发送GET请求
??? ??? String s = TestGetPost.sendGet("http://localhost:8888/abc/login.jsp",
??? ??? ??? ??? null);
??? ??? System.out.println(s);
??? ??? // 发送POST请求
??? ??? String s1 = TestGetPost.sendPost("http://localhost:8888/abc/a.jsp",
??? ??? ??? ??? "user=李刚&pass=abc");
??? ??? System.out.println(s1);

??? }
}

上面程序中发送GET请求时只需将请求参数放在URL字符串之后,以?隔开,程序直接调用URLConnection对象的connect方法即可,如程序中sendGet方法中粗体字代码所示;如果程序需要发送POST请求,则需要先设置doIn和doOut两个请求头字段的值,再使用 URLConnection对应的输出流来发送请求参数即可,如程序中sendPost方法中粗体字代码所示。
不管是发送GET请求,还是发送POST请求,程序获取URLConnection响应的方式完全一样:如果程序可以确定远程响应是字符流,则可以使用字符流来读取;如果程序无法确定远程响应是字符流,则使用字节流读取即可。
注意:上面程序中发送请求的两个URL是笔者在本机部署的Web应用,关于如何创建Web应用、编写JSP页面请参考笔者所著的《轻量级J2EE企业应用实战》。由于程序可以使用这种方式直接向服务器发送请求——相当于提交Web应用中的登陆表单页,这样就可以让程序不断地变换用户名、密码来提交登陆请求,直到返回登陆成功,这就是所谓的暴力破解。

读书人网 >操作系统

热点推荐