gpt4 book ai didi

java - 简单的POST请求/响应方法?

转载 作者:行者123 更新时间:2023-12-01 13:21:00 25 4
gpt4 key购买 nike

基本上,我想做的就是使用我定义的一些 POST 变量获取 PHP 页面的文本响应。

那么,将一些 POST 数据(例如“arg1=this&arg2=that”)发送到 URL 并将响应(内容,而不是 header )作为字符串处理的最简单方法是什么?

最佳答案

Use HttpUrlConnection to send a post request using java. attach your all parameter and in test.php prepare your response and return back to sender.

        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());
}
}

关于java - 简单的POST请求/响应方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22030902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com