`
420189155
  • 浏览: 52873 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

获取Url信息的四种请求

 
阅读更多

1、BufferedReader 

                URL url = new URL("http://qingni.net");

            // 读取源码

BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));

String line;

StringBuffer sb = new StringBuffer();

while ((line = reader.readLine()) != null) {

sb.append(line).append("\n");

}

reader.close();

2、InputStreamReader

 

                URL url = new URL("http://qingni.net");

// 读取源码

//读取中文时,使用Reader类是每次读出两个字节的,不会出现中文乱码

InputStreamReader in = new InputStreamReader(url.openStream(), "UTF-8");

char[] buf = new char[2048];//缓存

StringBuffer sb = new StringBuffer();

int len = 0;

while ((len = in.read(buf)) != -1) {//当没到文档尽头继续读取

sb.append(buf, 0, len);

}

 

3、HttpURLConnection 

 

     String line;

StringBuffer sb = new StringBuffer();

resp.setContentType("text/plain; charset=utf-8");

 

try {

URL url = new URL("http://qingni.net/");

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setDoInput(true);// 使用 URL 连接进行输入

connection.setRequestMethod("GET");

// 取得网页源码

BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));

if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {

// 每次读取一行输出

while ((line = reader.readLine()) != null) {

sb.append(line).append("\n");

}

reader.close();

} else {

// Server returned HTTP error code.

}

connection.disconnect();

} catch (MalformedURLException e) {

 

} catch (IOException e) {

 

}

 
4、HttpURLConnection  Post
            String line;
StringBuffer sb = new StringBuffer();
String result = null;
resp.setContentType("text/html; charset=utf-8");
 
try {
// 此处的地址请换成你的,在本地测试时可以填入http://localhost:8080/request.jsp
URL url = new URL("http://qingni.net/request.jsp");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);// 使用 URL 连接进行输出
connection.setRequestMethod("POST");
// 取得输出流
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
// 用UTF-8编码,保证中文传递正常
String message = URLEncoder.encode("你好,I'm Fatkun!", "UTF-8");
// 写入发送的内容 如 aaa=2222&bbb=3333 不带?号
writer.write("msg=" + message);
writer.close();
 
// 取得输入流并读出
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
log.info("成功连接");
// 每次读取一行输出
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
} else {
// Server returned HTTP error code.
}
 
connection.disconnect();
} catch (MalformedURLException e) {
 
} catch (IOException e) {
 
}
分享到:
评论
1 楼 dengminghua1016 2012-03-05  
终于找到了想要的……

相关推荐

Global site tag (gtag.js) - Google Analytics