首页 > 代码库 > HTTP-java模拟Get请求小栗子
HTTP-java模拟Get请求小栗子
1 import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStreamReader; 4 import java.net.HttpURLConnection; 5 import java.net.URL; 6 8 import javax.net.ssl.HttpsURLConnection;10 11 import org.apache.log4j.Logger;13 16 /* 17 * GET请求类,非线程类 18 */ 19 public class GetRequest { 20 private String url = "https://b2b.10086.cn/b2b/main/viewNoticeContent.html?noticeBean.id="; 21 private Logger logger; 22 public GetRequest() { 23 logger = Logger.getLogger(GetRequest.class); 24 } 25 26 public ExtendCandidate getData(String id) { 27 this.url = url + id; 28 BufferedReader in = null; 29 HttpURLConnection conn = null; 30 String result = ""; 31 try { 32 conn = (HttpURLConnection)new URL(url).openConnection(); 33 // 发送GET请求必须设置如下两行 34 conn.setDoInput(true); 35 conn.setRequestMethod("GET"); 36 // flush输出流的缓冲 37 in = new BufferedReader(new InputStreamReader(conn.getInputStream())); 38 String line; 39 while ((line = in.readLine()) != null) { 40 result += line; 41 } 42 } catch (Exception e) { 43 logger.error("发送 GET 请求出现异常!\t请求ID:"+id+"\n"+e.getMessage()+"\n"); 44 } finally {// 使用finally块来关闭输出流、输入流 45 try { 46 if (in != null) { 47 in.close(); 48 } 49 } catch (IOException ex) { 50 logger.error("关闭数据流出错了!\n"+ex.getMessage()+"\n"); 51 } 52 } 53 //获取到结果result,可以直接添加处理,或者存储到全局变量...... 54 } 55 }
java模拟Post请求: http://www.cnblogs.com/husky/p/6377553.html
HTTP-java模拟Get请求小栗子
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。