我寫一個小型的Java程序/ API以編程方式登錄/(做了高溫高壓後的登錄憑證)到這個http://web2sms.ke.airtel.comJava中,模擬瀏覽器
對我後,我需要的參數(key和value登錄表單)。當我通過瀏覽器呈現表單時,鍵/名每次都會改變,但是當我通過鍵下面的java代碼獲取頁面時總是聯繫f_1.number,因此意味着服務器在我看來服務器正在區分,如果頁面是從瀏覽器獲取或不從。我怎樣才能模擬一個瀏覽器並讓數據被瀏覽器渲染?
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
*
* @author Dell
*/
public class AirtelWeb2Sms {
String link = "http://web2sms.ke.airtel.com";
/**
* @param args the command line arguments
*/
private boolean on = false;
public static void main(String[] args) {
new AirtelWeb2Sms();
}
public AirtelWeb2Sms() {
login();
}
private void login(){
Map <String, String> parameters = new HashMap();
try{
URL url = new URL(link);
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
if(inputLine.contains("<div id=\"loginform\">"))
{
on=true;
}
if(on && (inputLine.contains("input")||inputLine.contains("select"))&& inputLine.contains("name")&& inputLine.contains("value")){
// System.out.println(inputLine);
String[] tokens = inputLine.split("\" ");
String key="", value="";
for(String str: tokens){
if(str.contains("name=")){
key=str.substring(str.indexOf("\"")+1);
}
if(str.startsWith("value")){
value=str.substring(str.indexOf("\"")+1);
}
if(key.contains(".number")){
value="+25473DummyNumber";
}
if(key.contains(".passwd")){
value="dymmerPassword";
}
if(key.contains(".language")){
value="en";
}
}
parameters.put(key, value=value.replace(""", "\""));
System.out.println(key+":"+value);
}
if(inputLine.contains("<input type=\"submit\""))
{
on=false;
}
}
doSubmit(link+"index.hei", parameters);
}
catch(Exception ex){
System.out.println(ex.getLocalizedMessage());
}
}
public void doSubmit(String url, Map<String, String> data) throws Exception
{
URL siteUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) siteUrl.openConnection();
conn.setRequestMethod("POST"); conn.setDoOutput(true);
conn.setDoInput(true); DataOutputStream out = new DataOutputStream(conn.getOutputStream());
Set keys = data.keySet();
Iterator keyIter = keys.iterator(); String content = "";
for(int i=0; keyIter.hasNext(); i++) {
Object key = keyIter.next();
if(i!=0) {
content += "&";
}
content += key + "=" +data.get(key);
}
System.out.println(content);
out.writeBytes(content);
out.flush();
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while((line=in.readLine())!=null) {
System.out.println(line); } in.close();
}
}
這當然取決於服務器 - 請給出更多的細節。另外,「我認爲服務器中的服務器是差分」是什麼意思? – jazzbassrob 2013-03-15 14:26:53
嗨,我的意思是區別,即服務器可以告訴它不從瀏覽器 – 2013-03-15 14:35:33