赞
踩
public OceanusResponseDTO<JSONObject> doApi(String rootUrl, Api api, JSONObject post) {
StringBuffer strBf = new StringBuffer();
try {
URL realUrl = new URL(rootUrl+api.getUrl());
HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
connection.connect();
DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
String query = post.toString();
//System.out.println(query); //能正常显示数据
dataout.write(query.getBytes("UTF-8"));
dataout.flush();
dataout.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String lines;
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
strBf.append(lines);
}
reader.close();
connection.disconnect();
System.out.println("返回数据:"+strBf.toString());
} catch (Exception e) {
e.printStackTrace();
}
return null;
URL请求的类别,分为GET和POST请求。二者区别是:
1)GET请求是把参数放在URL字串后,传递给servlet
2)POST请求是把参数放在http请求的正文内。一般是String字符串
URL realUrl = new URL(rootUrl+api.getUrl());
HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
这里realUrl打开URL连接,实则是生成HttpURLConnection对象,故可以直接转换为HttpURLConnection对象,以便使用更多的API
//设置是否向httpURLConnection输出,因为这个是post请求,参数要放在http正文内,故设为true
connection.setDoOutput(true);
//设置是否从httpURlConnection读入,默认情况下是true
connection.setDoInput(true);
//设置post请求
connection.setRequestMethod("POST");
//post请求不能使用缓存
connection.setUseCaches(false);
//设置httpURLConnection实例是否自动执行重定向
connection.setInstanceFollowRedirects(true);
//设置请求头里面的各个属性
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
//建立连接
connection.connect();
//创建输入输出流,用于 向连接里面 输出 携带的参数 (输出内容为 连接?后面的内容)
DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
String query = post.toString();
//将参数输出到连接
dataout.write(query.getBytes("UTF-8"));
//输出完成后刷新并关闭流
dataout.flush();
//重要步骤 勿忘
dataout.close();
//读取输出的流
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String lines;
//将读取的数据保存到lines这个字符串
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
strBf.append(lines);
}
//关闭流
reader.close();
//关闭连接
connection.disconnect();
//打印数据
System.out.println("返回数据:"+strBf.toString());
} catch (Exception e) {
e.printStackTrace();
}
return null;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。