Java socket模擬傳送和接收HTTP訊息
阿新 • • 發佈:2019-01-17
理解:模擬登陸指定網站,登陸成功後,獲取返回串中的cookie值用於發起下次請求。
package demo.http.client; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList; public class JavaHttpClient { // common parameters private static String serverIP = "192.168.30.205"; private static int serverPort = 80; private static String charset = "GBK"; // login parameters private static String loginUrl = "/picp/SecurityAction.do?method=login"; private static String loginNameIndex = "piUsersDto.usercode";// 使用者名稱索引 private static String loginPwdIndex = "piUsersDto.password";// 密碼索引 private static String loginName = "100001";//登陸使用者名稱 private static String loginPwd = "111111";//登陸密碼 private static String cookieIndex = "Set-Cookie: JSESSIONID=";//cookie索引串 // check operation parameters private static String checkUrl="/picp/SingleInquireAction.do?method=query"; private static String checkNameIndex="certname";//查詢名字索引 private static String checkIdNumIndex="certno";//查詢證件號碼索引 private static String checkType="businesscode";//查詢型別 public static void main(String[] args) { JavaHttpClient obj=new JavaHttpClient(); Socket clientSocket=null; try { clientSocket=new Socket(serverIP, serverPort); clientSocket.setSoTimeout(20*1000); //login String cookieValue=obj.login(clientSocket); if(cookieValue!=null){//check obj.checkOpt(clientSocket, cookieValue); } }catch (Exception e) { e.printStackTrace(); }finally{ if(clientSocket!=null){ try { clientSocket.close(); } catch (Exception e) { e.printStackTrace(); } } } }
/* 登陸操作,成功後返回cookie */ private String login(Socket clientSocket) { String cookieValue=null; try { String loginStr=createLoginReqStr(); clientSocket.getOutputStream().write(loginStr.getBytes(charset)); clientSocket.getOutputStream().flush(); String loginResponseStr=getResponseStr(clientSocket.getInputStream()); //判斷是否登陸成功 //end cookieValue=getCookieStr(loginResponseStr); }catch (Exception e) { e.printStackTrace(); } return cookieValue; }
/*組織登陸串*/ private String createLoginReqStr() { try { String loginStr = loginNameIndex + "=" + loginName + "&" + loginPwdIndex + "=" + loginPwd; StringBuffer sBuf = new StringBuffer(); sBuf.append("POST " + loginUrl + " " + "HTTP/1.1\r\n"); sBuf.append("Accept: "+ "text/html, application/xhtml+xml, */*\r\n"); sBuf.append("Accept-Language: zh_CN\r\n"); sBuf.append("Content-Type: application/x-www-form-urlencoded\r\n"); sBuf.append("Host: " + serverIP + ":" + serverPort + "\r\n"); sBuf.append("Content-Length: " + loginStr.getBytes(charset).length+"\r\n"); sBuf.append("Connection: Keep-Alive\r\n"); sBuf.append("Cache-Control: no-cache\r\n"); sBuf.append("\r\n"); sBuf.append(loginStr); return sBuf.toString(); } catch (Exception e) { e.printStackTrace(); } return null; }
/*查詢操作*/
private void checkOpt(Socket clientSocket,String cookieValue){
try {
String checkStr=createCheckReqStr(cookieValue);
clientSocket.getOutputStream().write(checkStr.getBytes(charset));
clientSocket.getOutputStream().flush();
String checkResponseStr=getResponseStr(clientSocket.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
/*組織查詢串*/
private String createCheckReqStr(String cookieValue) {
StringBuffer sBuf=new StringBuffer();
try {
String checkStr=checkType+"="+"01&"+checkNameIndex+"="+"熊大"+"&"+checkIdNumIndex+"="+"370785198910047763";
for(int i=1;i<5;i++){
checkStr=checkStr+"&"+checkNameIndex+"=&"+checkIdNumIndex+"=";
}
sBuf.append("POST " + checkUrl + " " + "HTTP/1.1\r\n");
sBuf.append("Accept: "+ "text/html, application/xhtml+xml, */*\r\n");
sBuf.append("Accept-Language: zh_CN\r\n");
sBuf.append("Content-Type: application/x-www-form-urlencoded\r\n");
sBuf.append("Host: " + serverIP + ":" + serverPort + "\r\n");
sBuf.append("Content-Length: " + checkStr.getBytes(charset).length+"\r\n");
sBuf.append("Connection: Keep-Alive\r\n");
sBuf.append("Cache-Control: no-cache\r\n");
sBuf.append("Cookie: JSESSIONID="+cookieValue+"\r\n");
sBuf.append("\r\n");
sBuf.append(checkStr);
} catch (Exception e) {
e.printStackTrace();
}
return sBuf.toString();
}
/*獲取返回值*/
private String getResponseStr(InputStream ins){
StringBuffer sBuf=new StringBuffer();
int contentLength=0;//儲存http header中contentLength的值
try {
String aLine=null;
do{
aLine=readFromStream(ins, 0);
if(aLine.contains("Content-Length")){
contentLength=Integer.parseInt(aLine.split(":")[1].trim());
}
sBuf.append(aLine);
}while(!aLine.equals("\r\n"));
sBuf.append(readFromStream(ins, contentLength));
} catch (Exception e) {
e.printStackTrace();
}
return sBuf.toString();
}
/* 從流中讀取指定長度的位元組,readLenth為0時,讀取一行 */
private String readFromStream(InputStream ins, int readLength) {
try {
byte tmpB;
byte[] byteArr;
if (readLength == 0) {// 讀取一行
ArrayList byteList = new ArrayList();
do {
tmpB = (byte) ins.read();
byteList.add(tmpB);
} while (tmpB != 10);// 判斷是否換行
byteArr = new byte[byteList.size()];
for (int i = 0; i < byteList.size(); i++) {
byteArr[i] = (Byte) byteList.get(i);
}
byteList.clear();
} else {// 讀取指定長度
int index = 0;
byteArr = new byte[readLength];
do {
byteArr[index] = (byte) ins.read();
index++;
} while (index < readLength);
}
return new String(byteArr, charset);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/*獲取cookie值*/
private String getCookieStr(String loginResponseStr){
String cookieValue=null;
try {
int index=loginResponseStr.indexOf(cookieIndex);
System.out.println(index);
if(index>-1){
cookieValue = loginResponseStr.substring(index + 23, index + 55);
}
} catch (Exception e) {
e.printStackTrace();
}
return cookieValue;
}
}