package tutorial;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
/**
* http读取器
* @author zhangyt
*/
public class HttpReader {
public static void main(String[] args) throws Exception {
URL url = new URL("http://www.126.com");
InputStream in = url.openStream();
//字节读取
byte[] b = new byte[256];
int n = -1;
while ((n = in.read(b)) != -1) {
//可以指定编码类型
//String str = new String(b, 0, n, "gbk");
String str = new String(b, 0, n);
System.out.print(str);
}
//按行读取
//可以指定编码类型
//InputStreamReader bin = new InputStreamReader(in, "gbk");
InputStreamReader bin = new InputStreamReader(in);
BufferedReader br = new BufferedReader(bin);
String str = null;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
}
}
以上是以get方式请求读取资源的代码片
下面是以post方式请求读取资源的代码片
package tutorial;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
/**
* 以post方式请求读取http资源
* @author zhangyt
*/
public class HttpReaderPost {
public static void main(String[] args) throws Exception {
//设定参数
String data = URLEncoder.encode("key1", "UTF-8") + "="
+ URLEncoder.encode("汉字了", "UTF-8");
// 发出post请求
URL realUrl = new URL("http://localhost:8080/webtest/ShowParmeters");
URLConnection conn = realUrl.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
//写参数到请求正文
wr.write(data);
wr.flush();
//返回的连接是基于http的连接,因为我们请求字符串开头是http
//这里进行转化是为了得到服务端返回代码
HttpURLConnection httpConn = (HttpURLConnection) conn;
//得到相关信息
//得到状态代码, 只有当 ResponseCode 为 2 开头的代码的时候, 才去处理我们想要的
//否则可以重新请求或者跳过,或者记录请求失败日志
System.out.println(httpConn.getResponseCode());
//得到返回类型
System.out.println(conn.getContentType());
//得到内容长度
System.out.println(conn.getContentLength());
//打印一个空行
System.out.println();
// 得到正文结果,并输出到控制台
BufferedReader rd = new BufferedReader(new InputStreamReader(conn
.getInputStream(), "utf-8"));
String line;
while ((line = rd.readLine()) != null) {
//做你想做的事情在这里
System.out.println(line);
}
//关闭读写流
wr.close();
rd.close();
}
}
网站经常会设置自动跳转。那么java客户端怎样得到跳转恢复代码呢。 直接用httpConn.getResponseCode()时不行的。这就需要我们设置httpConn.setInstanceFollowRedirects(false); 然后httpConn.getHeaderField("Location")得到将要跳转的页面url。例子如下
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpReader {
public static void main(String[] args) throws Exception {
URL url = new URL("http://localhost:8080/webtest/LookRedirect");
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setInstanceFollowRedirects(false);
System.out.println(httpConn.getResponseCode());
System.out.println(httpConn.getHeaderField("Location"));
}
}