0
基本上,我想要做的就是使用我定義的一些POST變量來獲取PHP頁面的文本響應。簡單的POST請求/響應方法?
那麼,將一些POST數據(比如「arg1 = this & arg2 = that」)發送到URL並將響應(內容,不是標頭)作爲字符串處理的最簡單方法是什麼?
基本上,我想要做的就是使用我定義的一些POST變量來獲取PHP頁面的文本響應。簡單的POST請求/響應方法?
那麼,將一些POST數據(比如「arg1 = this & arg2 = that」)發送到URL並將響應(內容,不是標頭)作爲字符串處理的最簡單方法是什麼?
使用HttpUrlConnection使用java發送發佈請求。附上你的所有參數,並在test.php準備你的回覆並返回給發件人。
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
private void sendPost() throws Exception
{
String url = "http://example.com/test.php";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0";);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "para1= xxx & para2=yy";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
if(responseCode == HTTP_OK)
{
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
}
更多詳情?。使用哪個平臺?或語言 –
你是什麼意思?我正在使用Eclipse和Java 7. – Zapk
http://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/ – Leo