<span style="white-space:pre"> </span>public static String readPostContent(String httpUrl, String content, String charSetName) {
StringBuilder sb = new StringBuilder();
BufferedReader reader = null;
try {
URL resourceUrl = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) resourceUrl.openConnection();
// 设置是否向connection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true
connection.setDoOutput(true);
// Read from the connection. Default is true.
connection.setDoInput(true);
// Set the post method. Default is GET
connection.setRequestMethod("POST");
// Post 请求不能使用缓存
connection.setUseCaches(false);
// URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
connection.setInstanceFollowRedirects(true);
// 表明urlencoded编码过的form参数
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset="+charSetName);
// 开始连接(连接前配置必须要完成,否则无效)
connection.connect();
PrintWriter out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(),charSetName));
out.println(content);
out.flush();
out.close(); // flush and close
// reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), charSetName));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
connection.disconnect();
} catch (MalformedURLException e) {
System.out.println("http请求时,URL(" + httpUrl + ")格式错误: "+ e);
e.printStackTrace();
} catch (ProtocolException e) {
System.out.println("http请求时,协议异常: "+ e);
e.printStackTrace();
} catch (IOException e) {
System.out.println("http请求时,IO异常: "+ e);
e.printStackTrace();
} finally {
if (null != reader)
try {
reader.close();
} catch (IOException e) {
}
}
return sb.toString();
}
后台发送http请求 类
最新推荐文章于 2023-07-12 16:33:03 发布