用java写post请求(添加post参数)

本文提供了一个使用Java发送POST请求并获取响应的示例代码。该示例详细展示了如何通过HttpURLConnection建立连接、设置请求头及请求参数,并读取服务器返回的数据。
[color=red]网址和参数需要根据自己的情况修改

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
[/color]

public static String getHtmlByPost(String urlString) throws IOException{

/*
* POST https://www.xxx.com
sign: 3149fa619b03988963bf1c53b8947f0e
Content-Type: application/x-www-form-urlencoded
Content-Length: 285
Host: www.xxx.com
Connection: Keep-Alive
Accept-Encoding: gzip
User-Agent: okhttp/3.2.0
_time=2017-12-15%2011%3A07%3A02&user_coordinate=116.307956%2C39.966622&coordinate=116.307956%2C39.966622&_osversion=6.0&radius=50000&_build=50&_platform=Android&_cityid=110100&_device=awiftb0%3A89%3A00%3A99%3A27%3Ae8&_version=3.8.3&page=1&channel=huijiachifan&size=10&_screen=1080x1810
*/
[color=blue]URL url = new URL(urlString);
//参数
StringBuilder parameterbulider = new StringBuilder();
//响应
StringBuilder responseBuilder = new StringBuilder();
BufferedReader reader = null;
PrintWriter out = null;

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setInstanceFollowRedirects(false);
//post 请求必须设置此处
conn.setDoOutput(true);
conn.setDoInput(true);

conn.setUseCaches(false);
conn.setDefaultUseCaches(false);
conn.setConnectTimeout(30 * 1000);//连接超时
conn.setReadTimeout(30 * 1000);//读取超市
conn.setRequestMethod("POST");

//多个参数拼接
parameterbulider.append("sign=3149fa619b03988963bf1c53b8947f0e");
parameterbulider.append("Content-Type=application/x-www-form-urlencoded");
parameterbulider.append("Content-Length=285");
parameterbulider.append("Host=www.xxx.com");
parameterbulider.append("Connection=Keep-Alive");
parameterbulider.append("Accept-Encoding=gzip");
parameterbulider.append("User-Agent=okhttp/3.2.0");
parameterbulider.append("_time=2017-12-15%2011%3A07%3A02&user_coordinate=116.307956%2C39.966622&coordinate=116.307956%2C39.966622&_osversion=6.0&radius=50000&_build=50&_platform=Android&_cityid=110100&_device=awiftb0%3A89%3A00%3A99%3A27%3Ae8&_version=3.8.3&page=2&channel=huijiachifan&size=10&_screen=1080x1810");


out = new PrintWriter(conn.getOutputStream());
out.print(parameterbulider.toString());
out.flush();

reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null)
{
responseBuilder.append(line + "\n");
}
reader.close();
String result = responseBuilder.toString();[/color]
return result;
}
[color=red] /**
测试*/[/color]
public static void main(String[] args) {
String url="https://www.xxx.com";
try {
System.out.println(getHtmlByPost(url));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
### 如何在Java中向POST请求添加查询参数 为了构建带有查询参数的HTTP POST请求,在Java中有多种方法可以实现这一功能。一种常见的方式是利用`HttpURLConnection`类,另一种更现代的方法则是采用像Apache HttpClient这样的库。 当使用`HttpURLConnection`时,可以通过URL字符串直接附加查询参数[^2]: ```java String query = String.format("fname=%s", URLEncoder.encode("test.txt", "UTF-8")); URL url = new URL("http://example.com/resource?" + query); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); ``` 对于更加复杂的场景或者需要更好的可维护性和易读性的代码来说,推荐使用HttpClient库。下面是一个基于此库的例子,展示了如何设置查询参数以及发送包含这些参数在内的POST请求: ```java import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.entity.StringEntity; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost postRequest = new HttpPost("http://targetwebsite.com/path?param1=value1&param2=value2"); // 如果还需要传递消息体,则继续如下操作 try { String json = "{\"key\":\"value\"}"; StringEntity entity = new StringEntity(json); postRequest.setEntity(entity); } catch (UnsupportedEncodingException e) { // handle exception } HttpResponse response = httpClient.execute(postRequest); ``` 值得注意的是,在实际应用开发过程中,通常会结合框架或工具包来简化网络通信的操作,比如Spring Framework中的RestTemplate或是OkHttp等第三方库。上述例子仅作为基础概念介绍之用。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值