外部链接POST传参--HttpURLConnection

 访问外部链接我经常用HttpURLConnection,今天记录下POST请求方便日后查找。

public static String send(String post,String url){

HttpURLConnection conn = null;
StringBuffer resultBuffer = null;
OutputStreamWriter osw = null;
BufferedReader br = null;

try {

URL realUrl = new URL(url);
// 打开和URL之间的连接
conn = (HttpURLConnection) realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("charset", "UTF-8");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);// post不能使用缓存     
conn.setRequestMethod("POST");
// 获取URLConnection对象对应的输出流
osw = new OutputStreamWriter(conn.getOutputStream());
// 发送请求参数  //post的参数 xx=xx&yy=yy


osw.write(post);
osw.flush();
//  返回数据 
resultBuffer = new StringBuffer();
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String temp;
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}

} catch (Exception e) {
// TODO: handle exception
System.out.println(e);
} finally {
if (osw != null) {
try {
osw.close();
} catch (IOException e) {
osw = null;
throw new RuntimeException(e);
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
}
}


return resultBuffer.toString();

}

测试

public static void main(String[] args){
String url="http://192.168.0.70:8555//main/pcver1/roleList//123";
String post="roleName=NULL&pageNumber=1&pageSize=5";
String rstr=send(post,url);
System.out.println("rstr:\r\n"+rstr);

}

结果


猜你喜欢

转载自blog.csdn.net/nvfuy/article/details/79867108