1.这里的结果是json类型的
public static String getjsonStr() {
URL getUrl;
// 请求地址返回的json类型响应
String result = "";
try {
// 地址和参数
String url = "http://192.168.1.121:8080/APS/servlet/MmsAskServlet?CPId=b&phone=12451454147&file=www.baidu.com";
getUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) getUrl
.openConnection();
connection.setConnectTimeout(300000); // 设置连接主机超时(单位:毫秒)
connection.setReadTimeout(300000); // 设置从主机读取数据超时(单位:毫秒)
// 打开连接
connection.connect();
// 取得输入流,并使用Reader读取
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream(), "utf-8"));// 设置编码,否则中文乱码
String lines;
while ((lines = reader.readLine()) != null) {
// lines = new String(lines.getBytes(), "utf-8");
result += lines;
// System.out.println(lines);
}
System.out.println(result);
// 解析json类型响应
JSONObject jsonObject = JSONObject.fromObject(result);
String resultCode = (String) jsonObject.get("resultCode");
System.out.println(resultCode);
reader.close();
// 断开连接
connection.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 根据拼凑的URL,打开连接,URL.openConnection函数会根据URL的类型,
// 返回不同的URLConnection子类的对象,这里URL是一个http,因此实际返回的是HttpURLConnection
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}