JAVA请求网页 代码

/**
 * url:  请求的网页地址
 * data: 提交的数据,填null使用get方法.
 */
public static String sendRequest(String url, String data) throws IOException {
		OutputStreamWriter out = null;
		BufferedReader reader = null;
		StringBuffer response = new StringBuffer();
		try {
			URL httpUrl = null; // HTTP URL类 用这个类来创建连接
			// 创建URL
			httpUrl = new URL(url);
			// 建立连接
			HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
			if (data == null)
				conn.setRequestMethod("GET");
			else
				conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			conn.setRequestProperty("Connection", "keep-alive");
			//conn.setRequestProperty("Cookie","");
			//conn.setRequestProperty("Origin", "http://www.baidu.com");
			conn.setRequestProperty("User-Agent",
					"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");

			conn.setUseCaches(false);// 设置不要缓存
			conn.setInstanceFollowRedirects(true);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.connect();
			
			// POST请求
			if (data != null) {
				out = new OutputStreamWriter(conn.getOutputStream());
				out.write(data);
				out.flush();
			}
			
			// 读取响应
			reader = new BufferedReader(
					new InputStreamReader(conn.getInputStream()
							, "utf-8")
					);
			String str = null;
			
			while ((str = reader.readLine()) != null) {
				//lines = new String(lines.getBytes(), "utf-8");
				//response += lines;
				response.append(str+"\r\n");
			}
			reader.close();
			// 断开连接
			conn.disconnect();

			// System.out.print(response.toString());

		} catch (Exception e) {
			System.out.println("发送 请求出现异常!" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (reader != null) {
					reader.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return response.toString();
	}

 

你可能感兴趣的:(JAVA)