URL myUrl = new URL(searchURL);
URLConnection myConn = (HttpURLConnection)myUrl.openConnection();
myConn.setRequestProperty("User-agent","Mozilla/4.0");
BufferedReader br = new BufferedReader(new InputStreamReader(myConn.getInputStream()));
myConn.setRequestProperty("User-agent","Baiduspider ( http://www.baidu.com/search/spider.htm)");
myConn.setRequestProperty("User-agent","Mozilla/4.0");
HttpURLConnection.setFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)");
HttpRequest request = new HttpRequest("http://服务器/1.jsp");
第一次使用的是GET方式
request.setMethod("GET");
紧接着进行一些请求的属性设置
request.setRequestHeader("Cache-Control", "no-cache");
这里保持连接,因为后面还要发送数据到服务器呢
request.setRequestHeader("Connection", "Keep-Alive");
下面是一些无关紧要的属性设置了。
request.setRequestHeader("Accept", "image/gif, image/x-xbitmap,
image/jpeg, image/pjpeg, application/vnd.ms-excel,
application/vnd.ms-powerpoint, application/msword, */*");
request.setRequestHeader("Accept-Encoding", "gzip, deflate");
request.setRequestHeader("Accept-Language", "en-au");
request.setRequestHeader("Referer", "http://服务器/1.jsp");
request.setRequestHeader("User-Agent", "Mozilla/4.0 (compatible;
MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3215; .NET
CLR 1.0.3705)");
构造好了连接请求,然后连接
request.connect();
紧接着提取Cookie值,在后文的post中可以用到。
String strCookie = request.getResponseHeader("Set-Cookie");
strCookie = strCookie.substring(0,strCookie.indexOf(";"));
下面通过循环查找,提取__VIEWSTATE的值
for ( int i = 0; i < nlist.getLength(); i++) {
node = nlist.item(i);
strName = getNodeAttributeValue(node,"name");
if ( strName.equals("__VIEWSTATE") ) {
strValue = getNodeAttributeValue(node,"value");
break;
}
}
往服务器组织发送数据
DataOutputStream dos = new DataOutputStream(request.getOutputStream());
dos.writeBytes("-----------------------------"+strBoundary);//这是每个要被发送数据间的间隔
dos.writeBytes("/r/nContent-Disposition: form-data; name=/"__VIEWSTATE/"");
dos.writeBytes("/r/n/r/n"+strValue);
dos.writeBytes("/r/n-----------------------------"+strBoundary);
这里面是发送文件的部分
dos.writeBytes("/r/nContent-Disposition: form-data;
name=/"uploadfile1/"; filename=/"" + strFileName + "/"");
dos.writeBytes("/r/nContent-Type: text/xml");
dos.writeBytes("/r/n/r/n");
dos.writeBytes(new String(data));
dos.writeBytes("/r/n-----------------------------"+strBoundary);
dos.writeBytes("/r/nContent-Disposition: form-data; name=/"Button1/"");
dos.writeBytes("/r/n上传");
dos.writeBytes("/r/n-----------------------------"+strBoundary+"--");
dos.writeBytes("/r/n");
dos.close();
httpurlconnection设置user-agent参数 做个记录,网上的一些摘记
最新推荐文章于 2023-12-21 15:53:06 发布