public static String geturl1(String geturl,String content) throws Exception {
//请求的webservice的url
URL url = new URL(geturl);
//创建http链接
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//设置请求的方法类型
httpURLConnection.setRequestMethod("POST");
//设置请求的内容类型
httpURLConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
//设置发送数据
httpURLConnection.setDoOutput(true);
//设置接受数据
httpURLConnection.setDoInput(true);
//发送数据,使用输出流
OutputStream outputStream = httpURLConnection.getOutputStream();
//发送的soap协议的数据
// String requestXmlString = requestXml("北京");
//String content = "user_id="+ URLEncoder.encode("13846", "gbk");
//发送数据
outputStream.write(content.getBytes());
//接收数据
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = in.readLine()) != null){
buffer.append(line);
}
String str = buffer.toString();
return str;
}
字符串转为json对象并获取其中属性
String addrJson = GnthkUtil.geturl1();
JSONObject jobjectaddr = JSON.parseObject(addrJson);
String addr=jobjectaddr.getJSONObject("result").getString("formatted_address");
如果获得的jsonobject的里面是数组
则:
@RequestMapping("/toProduct")
public String toProduct() {
try {
String addrJson = GnthkUtil.geturl("http://xxxxxxxxx", "");
JSONObject jsonObject = JSON.parseObject(addrJson);
JSONArray array = jsonObject.getJSONArray("result");
String string = jsonObject.getJSONArray("result").toJSONString();
for(int i=0;i<array.size();i++){
JSONObject job = array.getJSONObject(i); // 遍历 jsonarray 数组,把每一个对象转成 json 对象
System.out.println(job.get("pdtname"));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}