`

Java网络编程学习

 
阅读更多
package com.ghost.t20140504;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class JavaNetApiTest {
	
	public static void main(String args[]) {
		String urlTest = "http://ghods.iteye.com/";//注:URL得以/结尾
		
		// 发送GET请求
		String gets = JavaNetApiTest.sendGet(urlTest,null);
		System.out.println(gets);
		// 发送POST请求
//		String posts = TestGetPost.sendPost(urlTest,null);
//		System.out.println(posts);
//		openURL(urlTest);
	}
	
	/**
	 * 向指定URL发送GET方法的请求
	 * @param url  发送请求的URL
	 * @param param 请求参数,请求参数应该是name1=value1&name2=value2的形式。
	 * @return URL所代表远程资源的响应
	 */
	public static String sendGet(String url, String param) {
		StringBuffer result = new StringBuffer();
		BufferedReader in = null;
		try {
			URL realUrl = new URL(url + "?" + param);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36");
			conn.setRequestProperty("Accept-Language","zh-CN,zh;q=0.8,en;q=0.6");
			conn.setRequestProperty("Cookie","");
			// 建立实际的连接
			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.append(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.toString();
	}

	/**
	 * 向指定URL发送POST方法的请求
	 * @param url  发送请求的URL
	 * @param param 请求参数,请求参数应该是name1=value1&name2=value2的形式。
	 * @return URL所代表远程资源的响应
	 */
	public static String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		StringBuffer result = new StringBuffer();
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36");
			conn.setRequestProperty("Accept-Language","zh-CN,zh;q=0.8,en;q=0.6");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result.append(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.toString();
	}

	
	/**
	 * 利用操作系统的默认浏览器打开URL
	 * @param url
	 * @return
	 */
	 public static boolean openURL(String url) {
	        String osName = System.getProperty("os.name");  
	        try {  
	            if (osName.startsWith("Mac OS")) {  
	                //Mac OS  
	                Class<?> fileMgr = Class.forName("com.apple.eio.FileManager");  
	                Method openURL = fileMgr.getDeclaredMethod("openURL",  
	                        new Class[] { String.class });  
	                openURL.invoke(null, new Object[] { url });
	            } else if (osName.startsWith("Windows")) {
	                //Windows  
	                Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler "+ url);  
	            } else {  
	                //Unix or Linux  
	                String[] browsers = { "firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape" };  
	                String browser = null;  
	                for (int count = 0; count < browsers.length && browser == null; count++) {  
	                    if (Runtime.getRuntime().exec(new String[] { "which", browsers[count] }).waitFor() == 0) {  
	                        browser = browsers[count];  
	                    }
	                }  
	                if (browser != null) { 
	                    Runtime.getRuntime().exec(new String[] { browser, url });  
	                } 
	            }
	            return true ;  
	        } catch (Exception ex) {  
	            ex.printStackTrace();  
	            return false ;  
	        }  
	    }  
}

 

浏览器下的开发者工具是网页开发必备武器。以下是chrome查看请求http://ghods.iteye.com/时Network下的信息



 

  • 大小: 45.3 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics