java 发送http请求

String url="";//访问地址

String param="";//参数,若是json格式则为"{\"realm\":\"weixin.lenovo.com.cn\"}",

PrintWriter out = null;

BufferedReader in = null;

String result = "";

try {

URL realUrl = new URL(url);

URLConnection conn =realUrl.openConnection();

conn.setDoOutput(true);

conn.setDoInput(true);

out = new PrintWriter(conn.getOutputStream());

// 发送请求参数

out.print(param);

// flush输出流的缓冲

out.flush();

// 定义BufferedReader输入流来读取URL的响应

in = new BufferedReader(

new InputStreamReader(conn.getInputStream(),"UTF-8"));

String line;

while ((line = in.readLine()) != null) {

result += line;

}

} catch (Exception e) {

System.out.println("发送 POST 请求出现异常!"+e);

e.printStackTrace();

}finally{

try{

if(out!=null){

out.close();

}

if(in!=null){

in.close();

}

}

catch(IOException ex){

ex.printStackTrace();

}

}


你可能感兴趣的:(java,http请求)