说到java的网络编程,第一个想到的就是HttpURLConnection,它是用来和其他网站,在网络上交互的类。 可以通过它用GET或POST请求向其他服务器请求资源,反正是个非常好用的类,关于它的操作也非常简单,不多说,贴代码。
String url="http://172.16.13.93/student/public/login.asp";
URL loginUrl= newURL(url);
HttpURLConnection huc=(HttpURLConnection) loginUrl.openConnection();
huc.setRequestMethod("GET"); BufferedReader reader = new BufferedReader(new InputStreamReader( huc.getInputStream(),"gbk"));
String line;while ((line = reader.readLine()) != null){
System.out.println(line);
}
reader.close();
就这么短,就能向服务器请求资源。这是GET请求,只有GET请求的Url中要填什么参数,就看你实际情况了,一般用一些抓包工具,比如说Httpwatch 或者wireshark之类的去抓字段,POST请求 也是一样,来获取上传的参数的字段名。下面是POST请求的代码
public static void first(String url) throwsException{
Map paramsHashMap = new HashMap();//传值,这是从我要抓的网站要提供的3个参数,第三个参数是不变的,抓包抓到的
paramsHashMap.put("username", "1234");
paramsHashMap.put("password", "1234");
paramsHashMap.put("login", "%B5%C7%A1%A1%C2%BC");
firstRequest(url, paramsHashMap,"UTF-8"); }private static void firstRequest(String path, Map params, String encoding) throwsException{
StringBuilder sb= newStringBuilder();if(params!=null && !params.isEmpty()){for(Map.Entryentry : params.entrySet()){
sb.append(entry.getKey()).append('=');
sb.append(URLEncoder.encode(entry.getValue(), encoding));
sb.append('&'); }
sb.deleteCharAt(sb.length()- 1); }byte[] entity =sb.toString().getBytes();
HttpURLConnection conn= (HttpURLConnection) newURL(path).openConnection();
conn.setInstanceFollowRedirects(true);
conn.setConnectTimeout(5000);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
OutputStream outStream=conn.getOutputStream();
outStream.write(entity);//获取重定向地址
String redictURL= conn.getHeaderField( "Location");
System.out.println("第一次请求重定向地址 location="+redictURL);
System.out.println("第一次请求 conn.getResponseCode()="+conn.getResponseCode());
BufferedReader reader= new BufferedReader(newInputStreamReader(
conn.getInputStream(),"gbk"));
String line;while ((line = reader.readLine()) != null){
System.out.println(line);
}
}
这里可以看见与GET请求不同,这里多了个参数添加的函数,还有个关于网页重定向的问题。
参数那个注意的是要打开输出流,向网页提交要传送的参数,即conn.setDoOutput(true);
然后写入 OutputStream outStream = conn.getOutputStream(); outStream.write(entity);
有一点要提及,就是真正与网页连接是在conn.getInputStream();这段代码的时候,之前的操作都是还没有与网页交互。
可以看出用HttpURLConnection能方便的与网页进行基础的交互。 现在来说说重定向的问题。
重定向说白了就是通过各种的方法将各种网络请求重新定个方向转到其它位置。基本现在的网页都会弄个重定向。
你用账户和密码登陆某个网站之后,多半就会给你 重定向到另个网页。一般301 302之类以三开头的返回码就是重定向了的。
虽说用HttpURLConnetion也能对重定向进行处理,但是还是有限的。 所以推荐另个类,就是HttpClient了,这个类里面封装的很好,一般我们要从别人那里拉去数据,就要用账户和密码来获取SessionId,这个SessionId就相当于你的通行证了。
只要获得这个货,你就能将它设置在请求头中来获取各种数据。
但用HttpURLConnetion来获取SessionId经常会出错,我也找不到原因,看到网上的一些相关帖子,知道了一般关于Cookie和SessionId的操作用HttpClient来处理是最好的。 先说说HttpClient吧,HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。 首先你要使用它就要先下载它的jar包,个人只下了三个包
commons-codec-1.4.jar commons-httpclient-3.0.1.jar commons-logging-1.1.1.jar
下面来看看关于它的操作吧。
String SessionId="";
HttpClient client= newHttpClient();
PostMethod post= new PostMethod( "http://172.16.13.93/student/public/login.asp");
NameValuePair name= new NameValuePair( "username", username );
NameValuePair pass= new NameValuePair( "passwd", password );
NameValuePair login= new NameValuePair( "login" , "%B5%C7%A1%A1%C2%BC");
post.setRequestBody(new NameValuePair[]{name,pass,login}); int statusCode =client.executeMethod(post);if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode ==HttpStatus.SC_MOVED_TEMPORARILY) {//从头中取出转向的地址
Header locationHeader= post.getResponseHeader("location");if (locationHeader != null) {
Header sessionid= post.getResponseHeader("Set-Cookie");
String str=sessionid.getValue();
SessionId=str.substring(0,str.indexOf(";"));
}else{
System.err.println("Location field value is null.");
}
} post.releaseConnection();
这里是用的POST方法,用NameValuePair来处理传入参数的问题。GET请求也差不多这里就不多说了。
这样就又能处理重定向也能获取到Cookie。 如果你想获得完整的头信息的话 Header[] header = post.getResponseHeaders();就行。
获取到SessionId后将它加入到请求头中就可以获取了。
关于HttpClient就说到这里了。这里都是一些很浅显的用法,个人也专研的不深,大大们就不要来嘲讽了。