1, the write output should be read after the POST request, or an exception will be thrown.
That is, the operation OutputStream object should precede inputstreamreader.
2.conn.getresponsecode () Gets the return status code is best placed after reading and writing, otherwise it will throw an exception. It is not known whether this method will cause the connection to close and is to be verified.
The following code is posted on the tool class
Where get requests are stitched directly inside the Requesturl, post requests are passed through OUTPUTSTR.
/**
* Send HTTPS request
* @param requesturl Request Address
* @param Requestmethod Request Method (GET, POST)
* @param data submitted by OUTPUTSTR
* @return Jsonobject (key) to get the value of the JSON object's properties (Jsonobject.get)
*/
public static Wxapiresult Httpsrequest (String requesturl, String Requestmethod, String outputstr) {
Wxapiresult message = new Wxapiresult ();
try {
Trustmanager[] TM = {new Myx509trustmanager ()};
Sslcontext Sslcontext = sslcontext.getinstance ("SSL", "Sunjsse");
Sslcontext.init (NULL, TM, New Java.security.SecureRandom ());
Sslsocketfactory SSF = Sslcontext.getsocketfactory ();
URL url = new URL (requesturl);
Httpsurlconnection conn = (httpsurlconnection) url.openconnection ();
Conn.setsslsocketfactory (SSF);
Conn.setdooutput (TRUE);
Conn.setdoinput (TRUE);
Conn.setusecaches (FALSE);
Conn.setrequestmethod (Requestmethod);
if (null! = OUTPUTSTR) {
OutputStream outputstream = Conn.getoutputstream ();
Outputstream.write (Outputstr.getbytes ("UTF-8"));
Outputstream.close ();
}
InputStream InputStream = Conn.getinputstream ();
InputStreamReader InputStreamReader = new InputStreamReader (InputStream, "utf-8");
BufferedReader BufferedReader = new BufferedReader (InputStreamReader);
String str = NULL;
StringBuffer buffer = new StringBuffer ();
while ((str = bufferedreader.readline ()) = null) {
Buffer.append (str);
}
if (Conn.getresponsecode () ==conn. HTTP_OK) {
Message.setcode (0);
Message.setcontent (Buffer.tostring ());
}else{
Message.setcode (-1);
Message.setcontent ("Get return status is incorrect, return status is:" +conn.getresponsecode ());
}
Freeing resources
Bufferedreader.close ();
Inputstreamreader.close ();
Inputstream.close ();
InputStream = null;
Conn.disconnect ();
} catch (Connectexception CE) {
Log.error ("Connection timeout: {}", CE);
Message.setcode (-1);
Message.setcontent (Ce.getmessage ());
} catch (Exception e) {
Log.error ("https request exception: {}", E);
Message.setcode (-1);
Message.setcontent (E.getmessage ());
}
return message;
}
Java sends HTTP request data summary with raw HttpURLConnection