欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-04-24 17:18:26
...
网址和参数需要根据自己的情况修改

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;


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
*/
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();

return result;
}
/**
测试*/

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 url