package post;
import Java.io.BufferedReader;
import java.io.IOException;
import Java.io.InputStreamReader;
import Java.io.PrintWriter;
import Java.net.URL;
import java.net.URLConnection;
Public class dotest {
/**
* Request Connection Fixed parameters
* @param s pass-through address
*/
Public Static URLConnection getconnection (String s) throws IOException {
URL url = new URL (s);
URLConnection conn = Url.openconnection ();
Conn.setrequestproperty ("Accept", "Application/json"); Set the format for receiving data
Conn.setrequestproperty ("Content-type", "Application/json"); Format the sending data
return Conn;
}
Request address with interface address, request parameter is a JSON string, for example as follows:
Request Address: Http://127.0.0.1:8080/test/testone
Request parameter: {
"Testone": "Testname1",
"Testtwo": "Testname2"
// }
/**
* POST Request
* @param s pass-through address and interface
* @param param request Parameters
* @return return response results
* @throws IOException Throw exception
*/
Public Static String Reqpost (string s, string param) throws IOException {
System. out. println ("Request address:" +s);
System. out. println ("Request parameter:" +param);
String res = "";
URLConnection conn = getconnection(s); Post request URL does not contain request parameters
Conn.setdooutput (true); These two request properties must be set to true to indicate that the default is to use post to send
Conn.setdoinput (true);
The request parameter must use conn to obtain the OutputStream output to the request body parameter
PrintWriter out = new printwriter (Conn.getoutputstream ()); Packaging with a PrintWriter
Out.println (param);
Out.flush (); Immediately swipe to the request body) PrintWriter default is written in the memory cache first
try//Send a normal request (get resources)
{
BufferedReader in = new BufferedReader (
New InputStreamReader (Conn.getinputstream (), "Utf-8"));
String Line;
while (line = In.readline ()) = null) {
Res + = line + "\ n";
}
} catch (Exception e) {
System. out. println ("Get Error occured!");
E.printstacktrace ();
}
return Res;
}
}
HTTP protocol sends JSON string request