java代码post请求参数map字符串

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;


public static void main(String[] args) {
Map<String,String> map=new HashMap();
map.put("start","0");
map.put("limit","10");
String param= JSON.toJSONString(map);
//JSONObject object=JSON.parseObject(JSON.toJSONString(map))
    String postValue =  sendPost(url, param,8*1000,10*1000, Charset.forName("utf-8"));
System.out.println(postValue);
}


public static String sendPost(String url, String param,int connectTimeout,int readTimeout, Charset charset) {
try {
URL httpurl = new URL(url);
HttpURLConnection httpConn = (HttpURLConnection) httpurl.openConnection();
httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; "
+ "Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
httpConn.setConnectTimeout(8 * 1000);
httpConn.setReadTimeout(10 * 1000);
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setUseCaches(false);
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset.name());
httpConn.connect();
OutputStream outputStream = httpConn.getOutputStream();
PrintWriter out = new PrintWriter(outputStream);
out.print(param);
out.flush();
out.close();
InputStream inputStream = httpConn.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, charset.name()));
StringBuffer stringBuffer = new StringBuffer();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
String resp = stringBuffer.toString();
// System.out.println(resp);
if (stringBuffer != null) {
try {
bufferedReader.close();
} catch (IOException var18) {
var18.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException var17) {
var17.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException var17) {
var17.printStackTrace();
}
}
return resp;
}catch (IOException e) {
throw new RuntimeException(String.format("url:%s,param:%s,message:%s", url, param, e.getMessage()), e);
}
}
posted @   PZHZC  阅读(2851)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示