Java sendet GET- und Postanforderungen an den Server
Die Codekopie lautet wie folgt:
Paket com.hongyuan.test;
Import Java.io.BufferedReader;
importieren java.io.ioException;
importieren java.io.inputStreamReader;
Import Java.io.printwriter;
importieren java.net.httpurlConnection;
importieren java.net.url;
öffentliche Klasse httpclient {
// eine Get -Anfrage senden
öffentliche statische Zeichenfolge get (String Pfad) löst Ausnahme {aus {
HttpurlConnection httpconn = null;
BufferedReader in = null;
versuchen {
URL URL = neue URL (Pfad);
httpconn = (httpurlConnection) url.openconnection ();
// Lesen Sie die Antwort
if (httpconn.getResponSCode () == httpurlConnection.http_ok) {
StringBuffer content = new StringBuffer ();
String tempstr = "";
in = neuer BufferedReader (neuer InputStreamReader (httpconn.getInputStream ()));
while ((tempstr = in.readline ())! = null) {
content.Append (tempstr);
}
return content.toString ();
}anders{
Wirf eine neue Ausnahme ("Es gibt ein Problem mit der Anfrage!");
}
} catch (ioException e) {
E. printstacktrace ();
} Endlich{
in.close ();
httpconn.disconnect ();
}
null zurückkehren;
}
// Senden Sie eine GET -Anforderung, Parameterformular Key1 = value1 & key2 = value2 ...
public static String Post (String Pfad, String -Params) löst Ausnahme {aus {
HttpurlConnection httpconn = null;
BufferedReader in = null;
Printwriter out = null;
versuchen {
URL URL = neue URL (Pfad);
httpconn = (httpurlConnection) url.openconnection ();
httpconn.setRequestMethod ("post");
httpconn.setDoInput (true);
httpconn.setDooutput (true);
// POST -Anforderungsparameter senden
out = new printwriter (httpconn.getOutputStream ());
out.println (params);
out.flush ();
// Lesen Sie die Antwort
if (httpconn.getResponSCode () == httpurlConnection.http_ok) {
StringBuffer content = new StringBuffer ();
String tempstr = "";
in = neuer BufferedReader (neuer InputStreamReader (httpconn.getInputStream ()));
while ((tempstr = in.readline ())! = null) {
content.Append (tempstr);
}
return content.toString ();
}anders{
Wirf eine neue Ausnahme ("Es gibt ein Problem mit der Anfrage!");
}
} catch (ioException e) {
E. printstacktrace ();
} Endlich{
in.close ();
out.close ();
httpconn.disconnect ();
}
null zurückkehren;
}
public static void main (String [] args) löst Ausnahme {aus {
// String resmessage = httpclient.get ("http: // localhost: 3000/Hallo? Hallo = Hallo Get");
String resmessage = httpclient.post ("http: // localhost: 3000/hello", "Hallo = Hallo Post");
System.out.println (resmessage);
}
}