所以我有這段代碼,我得到它的工作,現在它基本上允許我發送http post並獲取我想要的幾乎任何外部網站的請求,除非這些元素不包含name屬性。這裏有一個例子:發送HTTP請求GET/POST以形成Java?
這是Java代碼:
public static String sendPostRequest(String url) {
StringBuffer sb = null;
try {
String data = URLEncoder.encode("user", "UTF-8") + "="
+ URLEncoder.encode("myUserName", "UTF-8") + "&"
+ URLEncoder.encode("submit", "UTF-8") + "="
+ URLEncoder.encode("Submit", "UTF-8");
URL requestUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) requestUrl
.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("GET");
OutputStreamWriter osw = new OutputStreamWriter(
conn.getOutputStream());
osw.write(data);
osw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String in = "";
sb = new StringBuffer();
while ((in = br.readLine()) != null) {
sb.append(in + "\n");
}
osw.close();
br.close();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
這是我想要的請求發送到形式(這是在W3Schools的網站形式,這是該網站http://www.w3schools.com/html/html_forms.asp):
<form name="input0" target="_blank" action="html_form_action.asp" method="get">
Username:
<input type="text" name="user" size="20" />
<input type="submit" value="Submit" />
</form>
現在因爲提交按鈕不具有name屬性,我無法發送正確的HTTP GET/POST請求,它(我知道這是在這種情況下,get方法)。我用什麼方法(什麼正確的鍵/值)替換字符串數據,以便它實際發送請求到這個表單?
這是如何在相對於什麼,我試圖做什麼辦法?我在問什麼鍵/值應該用來發送HTTP POST請求到特定的站點...不是關於某種API – ZimZim 2012-03-31 10:03:56
@ user1007059:HttpClient會給你更好的可讀性,你可以解決你的問題...我在我的項目中使用這個httpclien 4.1,並從任何URL獲取數據。 – 2012-03-31 10:35:40