通过HttpURLConnection调用接口

时间:2021-04-05 11:50:38   收藏:0   阅读:0
 1 URL realurl  = new URL(REQUESTURL); //REQUESTURL为常量,请求地址
 2 HttpURLConnection httpURLConnection = (HttpURLConnection) realurl.openConnection();
 3 httpURLConnection.setRequestMethod("POST");
 4 httpURLConnection.setRequestProperty("Content-type","application/json");
 5 httpURLConnection.setDoInput(true);
 6 httpURLConnection.setDoOutput(true);
 7 DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());
 8 out.write(info.toString().getBytes("UTF-8")); //info为JSONObject类型,为请求参数,格式为{"entity":{"id":"123456","name":"levi"}}
 9 out.flush();
10 out.close();
11 InputStream inputStream = httpURLConnection.getInputStream();   
12 String byteArrayOutputStream = streamToString(inputStream);    //streamToString为一个转化方法,将inputStream 类型转为String类型
13 JSONObject result = JSONObject.parseObject(byteArrayOutputStream);

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!