java代码 发送GET、POST请求 (二)

2014-11-24 10:36:24 · 作者: · 浏览: 1
SONDataFromURL(String url, String params) {
long begin = System.currentTimeMillis();
LOG.info("request:" + url);
JSONObject jsonObj = null;

HttpURLConnection huc = null;
BufferedReader in = null;
InputStreamReader isr = null;
InputStream is = null;

StringBuffer sb = new StringBuffer(333);

try {

URL u = new URL(url);
huc = (HttpURLConnection) u.openConnection();
huc.setRequestMethod("POST");
huc.setDoOutput(true);
huc.getOutputStream().write(params.getBytes("utf-8"));
huc.getOutputStream().flush();
huc.getOutputStream().close();
is = huc.getInputStream();
isr = new InputStreamReader(is, "utf-8");
in = new BufferedReader(isr);
String line = null;

while ((line = in.readLine()) != null) {
sb.append(line);
}

long end = System.currentTimeMillis();
LOG.info("response[" + (end - begin) + "]:" + sb.toString());
jsonObj = new JSONObject(sb.toString());

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
try {
huc.disconnect();
is.close();
isr.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}

return jsonObj;
}