Java利用 URLConnection发起Post请求并携带参数的方法
现在涉及到第三方对接方面功能时很多第三方平台为了安全使用的都是https请求,传统的发起http请求的方法就不再适用了,但使用原生的URLConnection方法来进行调用效果确是非常不错的,接下来就来介绍一下它的使用方法。
String url = "https://xxx-你的请求地址"; URL serverUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) serverUrl.openConnection(); // 设置是否向connection输出,因为这个是post请求,参数要放在 // http正文内,因此需要设为true conn.setDoOutput(Boolean.TRUE); conn.setDoInput(Boolean.TRUE); //请求方式是POST conn.setRequestMethod("POST"); // Post 请求不能使用缓存 conn.setUseCaches(false); conn.setRequestProperty("Content-type", "application/json"); //必须设置false,否则会自动redirect到重定向后的地址 conn.setInstanceFollowRedirects(false); //建立连接 conn.connect(); //设置请求体 HashMap map=new HashMap(); //key-value的形式设置请求参数 map.put("key","value"); String s = JSONObject.toJSONString(map); //获取了返回值 String result = HttpsUtils.getReturn(conn,s); //如果返回值是标准的JSON字符串可以像我这样给他进行转换 JSONObject jsonObject = JSONObject.parseObject(result);
HttpsUtils工具类
public class HttpsUtils { /*请求url获取返回的内容*/ public static String getReturn(HttpURLConnection connection) throws IOException { StringBuffer buffer = new StringBuffer(); //将返回的输入流转换成字符串 try(InputStream inputStream = connection.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader);){ String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } String result = buffer.toString(); return result; } } //post请求的方法重载 public static String getReturn(HttpURLConnection connection,String jsr){ try{ StringBuffer buffer = new StringBuffer(); byte[] bytes = jsr.getBytes(); OutputStream outputStream = connection.getOutputStream(); outputStream.write(bytes); outputStream.flush(); outputStream.close(); //将返回的输入流转换成字符串 InputStream inputStream = connection.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } String result = buffer.toString(); return result; }catch (Exception e){ log.error("postUrlConnection出错",e); } return null; } }