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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM