開發:隨筆記錄之 HTTP 呼叫

執筆記憶的空白發表於2014-04-25
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已經寫好, 需要的人直接複製貼上便可用。  如果覺得有用請回復一下。  允許轉載,但必須標明出處

相關文章