1创建URL
URL url= new URL("接口连接地址urlStr");
2.通过URL打开连接 HttpURLConnection.
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
如果采取get的方式请求 直接将参数写到url中
3.设置请求方式
1).如果是GET请求方式 在第一步创建URL的时候直接将参数放入url中
connection.setRequestMethod("GET");
urlStr="www.baidu.com?name=zyh&sex=男"
2).如果是POST请求方式
connection.setRequestMethod("POST");
connection.setDoOutput(true);//应用程序要将数据写入 URL 连接。
准备参数
JsonObject param=new JsonObject();
param.addProperty("name","zyh");
param.addProperty("sex","男");
写入参数
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStreamWriter outputStreamWriter =new OutputStreamWriter (connection.getOutputStream,"UTF-8" );
outputStreamWriter .write(param.toString());
outputStreamWriter .flush();;
4.通过连接connection获得流数据
InputStreamReader inputStreamReader =new InputStreamReader (connection.getInputStream(),"UTF-8");
BufferReader reader =new BufferReader (inputStreamReader);
5.读取并转为字符串 获得所需要的结果
StringBuffer result=new StringBuffer() ;
String temp;
while((temp=reader.readLine())!=null){
result.append(temp);
}
6.关闭流
outputStreamWriter.close();
reader.close();
萌新自用
有不对的地方求各位大佬指出