public class HttpUtil {

static Logger log = Logger.getLogger(HttpUtil.class);

public static String send(String callURL,String postData) throws Exception {

log.info("call url is:" + callURL);
log.info("call postData is:" + postData);
try {
URL url = new URL(callURL);
HttpURLConnection connection = null;
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
DataOutputStream out = new DataOutputStream(connection
.getOutputStream());

out.write(postData.getBytes("UTF-8"));
out.flush();
out.close();
int rc = connection.getResponseCode();
log.info("connect result is:" + rc);
// 响应成功
if (rc == 200) {
String temp;
InputStream in = null;
in = connection.getInputStream();
BufferedReader data = new BufferedReader(new InputStreamReader(
in, "utf-8"));
StringBuffer result = new StringBuffer();
while ((temp = data.readLine()) != null) {
result.append(temp);
temp = null;
}
data.close();
in.close();
log.info("returnData is:" + result.toString());
return result.toString();
}
} catch (IOException io) {
log.error(io.toString());
throw io;
} catch (Exception e) {
log.error(e.getMessage());
throw e;
}
return null;
}
}
想用http方式调用的util已经写好, 需要的人直接复制粘贴便可用。 如果觉得有用请回复一下。 允许转载,但必须标明出处