最近有个需求是需要在java中以GET方式去请求网址获取返回数据,就写出来共享一下。直接上码
/*
get方式访问网址
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlName = url + "?" + param;
URL realUrl = new URL(urlName);
//打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
//设置通用的请求属性
conn.setRequestProperty("accept", "charset=UTF-8");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
//建立实际的连接
conn.connect();
//定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in .readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
//使用finally块来关闭输入流
finally {
try {
if ( in != null) { in .close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
//提供主方法,测试发送GET请求
public static void main(String args[]) throws ParseException {
//发送GET请求
String s = STicketController.sendGet("https://www.baidu.com", "q=泰山");
//String转为JSON
JSONObject jsonObj = (JSONObject)(new JSONParser().parse(s));
System.out.println(jsonObj.get("data"));
}注意:1、如果String不转为JSON,result里面的中文是unicode格式的(也可能是我的请求问题)。
2、param直接以字符串格式传入即可。
版权声明:本文为gaochenglong1原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。