(Java)使用Java发送带参数的http(GET)请求,获取json数据
·
public String getCustomerInfo(Map<String, Object> map)
{
String appId = (String)map.get("appId");
String name = (String)map.get("name");
JSONObject jsonObject = null;
OutputStreamWriter out = null;
StringBuffer buffer = new StringBuffer();
try {
//1.连接部分
URL url = new URL("https://a.abc.com");
// http协议传输
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod("GET");
httpUrlConn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
//2.传入参数部分
// 得到请求的输出流对象
out = new OutputStreamWriter(httpUrlConn.getOutputStream(),"UTF-8");
// 把数据写入请求的Body
out.write("appId=" + appId + "&name=" + name); //参数形式跟在地址栏的一样
out.flush();
out.close();
//3.获取数据
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject.toString();
}
新一代开源开发者平台 GitCode,通过集成代码托管服务、代码仓库以及可信赖的开源组件库,让开发者可以在云端进行代码托管和开发。旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。
更多推荐

所有评论(0)