Java sends get and POST requests to the server
Copy Code code as follows:
Package com.hongyuan.test;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.PrintWriter;
Import java.net.HttpURLConnection;
Import Java.net.URL;
public class HttpClient {
Send a GET request
public static string get (String path) throws exception{
HttpURLConnection Httpconn=null;
BufferedReader In=null;
try {
URL url=new url (path);
Httpconn= (HttpURLConnection) url.openconnection ();
Read response
if (Httpconn.getresponsecode () ==HTTPURLCONNECTION.HTTP_OK) {
StringBuffer content=new StringBuffer ();
String tempstr= "";
In=new BufferedReader (New InputStreamReader (Httpconn.getinputstream ()));
while ((Tempstr=in.readline ())!=null) {
Content.append (TEMPSTR);
}
return content.tostring ();
}else{
throw new Exception ("There is a problem with the request!");
}
catch (IOException e) {
E.printstacktrace ();
}finally{
In.close ();
Httpconn.disconnect ();
}
return null;
}
Send a GET request, Parameter form key1=value1&key2=value2 ...
public static string post (string path,string params) throws exception{
HttpURLConnection Httpconn=null;
BufferedReader In=null;
PrintWriter Out=null;
try {
URL url=new url (path);
Httpconn= (HttpURLConnection) url.openconnection ();
Httpconn.setrequestmethod ("POST");
Httpconn.setdoinput (TRUE);
Httpconn.setdooutput (TRUE);
Send POST request parameters
Out=new PrintWriter (Httpconn.getoutputstream ());
OUT.PRINTLN (params);
Out.flush ();
Read response
if (Httpconn.getresponsecode () ==HTTPURLCONNECTION.HTTP_OK) {
StringBuffer content=new StringBuffer ();
String tempstr= "";
In=new BufferedReader (New InputStreamReader (Httpconn.getinputstream ()));
while ((Tempstr=in.readline ())!=null) {
Content.append (TEMPSTR);
}
return content.tostring ();
}else{
throw new Exception ("There is a problem with the request!");
}
catch (IOException e) {
E.printstacktrace ();
}finally{
In.close ();
Out.close ();
Httpconn.disconnect ();
}
return null;
}
public static void Main (string[] args) throws Exception {
String resmessage=httpclient.get ("Http://localhost:3000/hello?hello=hello get");
String resmessage=httpclient.post ("Http://localhost:3000/hello", "Hello=hello post");
System.out.println (Resmessage);
}
}