我正在使用HttpURLConnection通過POST將數據發送到服務器。我設置了標題,然後獲取輸出流並寫入一些字節,然後關閉輸出流。Java HttpURLConnection發佈方法不起作用
我想從給定的網址獲取下一頁計劃詳情。但一些我沒有得到結果。如果您知道此代碼中的任何問題,請幫助任何人。
我得到第一頁錯誤,而不是第二頁。 「您選擇的車站組合無效,請致電(718)217-5477聯繫LIRR旅遊信息中心,並索取代表以獲取更多信息。」
public static void main(String[] args) throws Exception {
String url = "http://lirr42.mta.info";
String cookie = retrieveCookies(url);
String urlParameters = "FromStation=56&ToStation=8&RequestDate=08/24/2013&RequestTime=01:00&RequestAMPM=PM&sortBy=1&schedules=schedules";
String page = postHttpPage(url + "/index.php", urlParameters, cookie);
System.out.println(page);
System.out.println();
}
public static String postHttpPage(String url, String urlParameters, String cookie) throws Exception {
System.out.println("\nSending 'POST' request to URL : " + url);
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
return postPage(conn, urlParameters, cookie);
}
private static String postPage(HttpURLConnection conn, String urlParameters, String cookie) throws Exception {
conn.setRequestMethod("POST");
conn.setRequestProperty("User-Agent", "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(urlParameters.getBytes().length));
conn.setRequestProperty("Content-Language", "en-US");
conn.setRequestProperty("Cookie", cookie);
//conn.setInstanceFollowRedirects(true);
// Send post request
//conn.setDoInput(true);
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(urlParameters);
//System.out.println("wr : " + wr.size());
wr.flush();
wr.close();
StringBuffer response = new StringBuffer();
int responseCode = conn.getResponseCode();
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
public static String retrieveCookies(String url) throws IOException{
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
String cookies=conn.getHeaderField("Set-Cookie");
System.out.print("cookies: " + cookies);
conn.disconnect();
return cookies;
}
你會得到什麼結果?你應該發佈。 – BlackHatSamurai
我得到第一頁錯誤,而不是第二頁。 **「您選擇的車站組合無效,請致電(718)217-5477聯繫LIRR旅遊信息中心,並索取代表以獲取更多信息。」** – user2589193