การคัดลอกรหัสมีดังนี้:
-
* เนื่องจาก fileutils ไม่รองรับให้เพิ่ม method string content =
* fileutils.readFileToString (fileutils.tofile (ใหม่
* url ("http://www.baidu.com"))));
-
* @param แหล่งที่มา
* @param การเข้ารหัส
* @กลับ
* @throws ioexception
-
String String สาธารณะ readurlToString (แหล่งที่มาของ URL) พ่น IOException {
return readurltoString (แหล่งที่มา null);
-
-
* เนื่องจาก fileutils ไม่รองรับเพิ่มวิธีการ
-
* <pre>
* String Content = FileUts.ReadFileToString (fileutils.tofile (URL ใหม่ (
* http://www.baidu.com)), gb2312);
* </der>
-
* @param แหล่งที่มา
* @param การเข้ารหัส
* @กลับ
* @throws ioexception
-
String String สาธารณะ readurlToString (แหล่งที่มาของ URL, การเข้ารหัสสตริง)
โยน ioexception {
inputstream อินพุต = source.openstream ();
พยายาม {
return ioutils.toString (อินพุต, การเข้ารหัส);
} ในที่สุด {
ioutils.closequietly (อินพุต);
-
-
-
* อ่านเนื้อหาของ URL (วิธีการโพสต์สามารถระบุพารามิเตอร์หลายตัวได้)
* @param url
* @param การเข้ารหัส
* @param พารามิเตอร์แผนที่พารามิเตอร์ (คีย์คือชื่อพารามิเตอร์ค่าคือค่าพารามิเตอร์)
* @return String
* @throws ioexception
-
String String สาธารณะ readurlToStringBypost (URL URL, การเข้ารหัสสตริง, แผนที่ <สตริง, สตริง> พารามิเตอร์)
โยน ioexception {
httpurlConnection con = null;
// สร้างพารามิเตอร์คำขอ
StringBuffer sb = new StringBuffer ();
if (params! = null) {
สำหรับ (รายการ <string, string> e: params.entryset ()) {
sb.append (e.getKey ());
sb.append ("=");
sb.append (e.getValue ());
sb.append ("&");
-
if (sb.length ()> 0) {
sb.substring (0, sb.length () - 1);
-
-
// พยายามส่งคำขอ
พยายาม {
con = (httpurlconnection) url.openconnection ();
con.setRequestMethod ("โพสต์");
Con.setDoOutput (จริง);
Con.setDoInput (จริง);
Con.setUsecaches (เท็จ);
Con.setRequestProperty ("ประเภทเนื้อหา", "แอปพลิเคชัน/X-WWW-FORM-URLENCODED");
OutputStreamWriter OSW = New OutputStreamWriter (Con.getOutputStream (), การเข้ารหัส);
if (params! = null) {
OSW.WRITE (SB.TOSTRING ());
-
OSW.FLUSH ();
OSW.CLOSE ();
} catch (Exception e) {
logfactory.getLog (fileutils.class) .error ("โพสต์ ("+url.toString ()+") ข้อผิดพลาด ("+e.getMessage ()+")", e);
} ในที่สุด {
ถ้า (con! = null) {
Con.disconnect ();
-
-
// อ่านเนื้อหาส่งคืน
StringBuffer buffer = new StringBuffer ();
พยายาม {
bufferedReader br = new bufferedReader (ใหม่ inputStreamReader (con
.getInputStream (), การเข้ารหัส));
สตริงอุณหภูมิ;
ในขณะที่ ((temp = br.readline ())! = null) {
buffer.append (temp);
buffer.append ("/n");
-
} catch (Exception e) {
E.PrintStackTrace ();
-
return buffer.toString ();
-