本文主要是介绍Java中HttpURLConnection的使用示例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Java中HttpURLConnection的使用示例
1.测试获取百度首页文本内容并输出:
public class TestUrlConnection {/*** 测试获取百度首页文本内容并输出* */public static void main(String[] args) throws Exception {String link = "http://www.baidu.com";URL url = new URL(link);HttpURLConnection urlCon = (HttpURLConnection)url.openConnection();urlCon.setReadTimeout(5 * 1000);urlCon.setRequestMethod("GET");InputStream is = urlCon.getInputStream();InputStreamReader isr = new InputStreamReader(is);BufferedReader br = new BufferedReader(isr);String inputLine;StringBuilder result = new StringBuilder("");if((inputLine = br.readLine()) != null){result.append(inputLine);}System.out.println(result);urlCon.disconnect();}
}
2.使用代理:
/*** 测试使用代理* */
public class MyProxy {public static InputStream getProxy(String url){try {//设置代理SocketAddress addr = new InetSocketAddress("127.0.0.1",8087);Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); URL url_ = new URL(url);InputStream stream = (InputStream)url_.openConnection(proxy).getInputStream();return stream;} catch (Exception e) {e.printStackTrace();return null;} }
}
3.测试解析从页面获得的json对象:
下面的示例是调用百度地图的api获得某一地址所对应的地理坐标(经纬度值及相关的参数),百度地图api返回的json对象格式如下:
{status: 0,result: {location: {lng: 116.30814954222,lat: 40.056885091681},precise: 1,confidence: 80,level: "商务大厦"}
}
/*** 测试解析从页面获得的json对象*/public static void main(String[] args) throws Exception {String link = "http://api.map.baidu.com/geocoder/v2/?address=清华大学&city=北京市&output=json&ak=foPosAdfuOAaNz8zc5964bFw&callback=showLocation";URL url = new URL(link);HttpURLConnection urlCon = (HttpURLConnection)url.openConnection();urlCon.setReadTimeout(5 * 1000);urlCon.setRequestMethod("GET");InputStream is = urlCon.getInputStream();InputStreamReader isr = new InputStreamReader(is,"UTF-8");BufferedReader br = new BufferedReader(isr);String inputLine;StringBuilder result = new StringBuilder("");if((inputLine = br.readLine()) != null){result.append(inputLine);}
// System.out.println(result);urlCon.disconnect();br.close();String result_ = result.toString().trim();String jsonStr = result_.substring(27, (result_.length() - 1));//System.out.println(jsonStr);JSONObject rootNode = new JSONObject(jsonStr); // System.out.println(rootNode); int status = rootNode.getInt("status");//返回结果状态值, 成功返回0if (status == 0){//如果返回成功JSONObject resultNode = (JSONObject) rootNode.get("result");int precise = resultNode.getInt("precise");//精度,位置的附加信息,是否精确查找。1为精确查找,0为不精确int confidence = resultNode.getInt("confidence");//可信度String level = resultNode.getString("level");//地址类型JSONObject locationNode = (JSONObject) resultNode.get("location");double lng = locationNode.getDouble("lng");//经度double lat = locationNode.getDouble("lat");//纬度System.out.println("status:" + status + '\t' + "precise:" + precise + '\t' + "confidence:" + confidence + '\t' + "level:" + level +'\n' + "lng:" + lng + '\t' + "lat:" + lat);}}
}
这篇关于Java中HttpURLConnection的使用示例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!