最近写的restful风格接⼝(post请求)
//发送post请求的⽅法,这个⽅法直接调⽤就⾏,url的值是固定的,难点在于param字符串参数拼接,个⼈的建议是,如果是json的形式,先在postman上⾯跑⼀下,然后把参数复制到idea上,会⾃动拼接
public static String insureResponsePost(String url, String param) {
PrintWriter out = null;
InputStream is = null;
BufferedReader br = null;
String result = "";
HttpURLConnection conn = null;
StringBuffer strBuffer = new StringBuffer();
try {
URL realUrl = new URL(url);
conn = (HttpURLConnection) realUrl.openConnection();
// 设置通⽤的请求属性
conn.setRequestMethod( "POST");
conn.setConnectTimeout(20000);
conn.setReadTimeout(300000);
conn.setRequestProperty("Charset", "UTF-8");
// 传输数据为json,如果为其他格式可以进⾏修改
conn.setRequestProperty( "Content-Type", "application/json");
conn.setRequestProperty( "Content-Encoding", "utf-8");
// 发送POST请求必须设置如下两⾏
conn.setDoOutput( true);
conn.setDoInput( true);
conn.setUseCaches( false);
// 获取URLConnection对象对应的输出流
out = new OutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
is = InputStream();
br = new BufferedReader( new InputStreamReader(is));
String line = null;
while ((adLine())!= null) {
strBuffer.append(line);
}
result = String();
} catch (Exception e) {
System. out.println( "发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使⽤finally块来关闭输出流、输⼊流
finally {
try {
if (out != null) {
out.close();
}
if (br != null) {
br.close();
}
restful接口详解if (conn!= null) {
conn.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。