During the httpurlconnection interaction process, the client needs to submit the sessionid when the server saves the session. Therefore, the server needs to store the sessionid. Each time it is uploaded, the server sessionid will not be lost.
Public static string dopost (string requrl, string parameters,
String recvencoding ){
System. Out. println ("Request:" + parameters );
Httpurlconnection url_con = NULL;
String responsecontent = NULL;
If (recvencoding. isempty () | recvencoding = NULL ){
Recvencoding = "UTF-8 ";
}
Try {
Stringbuffer Params = new stringbuffer ();
// The Chinese Garbled text parameter must be encoded in Chinese. Step 1 is followed by
Params. append ("P =" + urlencoder. encode (parameters, "UTF-8 "));
URL url = new URL (requrl );
//****************************
Url_con = (httpurlconnection) URL. openconnection ();
Object objsid = actioncontext. getcontext (). getsession (). Get ("Sid ");
// Determine whether sessionid exists;
If (objsid! = NULL ){
Url_con.setrequestproperty ("cookie", objsid. tostring ());
}
Url_con.setrequestmethod ("Post ");
Url_con.setconnecttimeout (500000); // (unit: milliseconds) JDK 1.5 is replaced with this, and the connection times out.
Url_con.setreadtimeout (500000); // (unit: milliseconds) JDK 1.5 is replaced with this, and the read operation times out.
Url_con.setdooutput (true );
Byte [] byteparams = Params. tostring (). getbytes ();
// Getbytes must be encoded to ensure that the parameter can be uploaded to the server without garbled characters.
Url_con.getoutputstream (). Write (parameters. getbytes ("UTF-8 "));
Url_con.getoutputstream (). Flush ();
Url_con.getoutputstream (). Close ();
// System. Out. println (url_con.getresponsecode ());
Inputstream in = url_con.getinputstream ();
String cookieval = url_con.getheaderfield ("Set-cookie ");
If (cookieval! = NULL ){
// Store sessionid;
String SID = cookieval. substring (0, cookieval. indexof (";"));
If (Sid! = NULL &&! Sid. isempty ()){
Actioncontext. getcontext (). getsession (). Put ("Sid", Sid );
}
}
Bufferedreader RD = new bufferedreader (New inputstreamreader (in,
Recvencoding ));
String templine = RD. Readline ();
Stringbuffer tempstr = new stringbuffer ();
String CRLF = system. getproperty ("line. separator ");
While (templine! = NULL ){
Tempstr. append (templine );
Tempstr. append (CRLF );
Templine = RD. Readline ();
}
Responsecontent = tempstr. tostring ();
Rd. Close ();
In. Close ();
} Catch (ioexception e ){
// Logger. Error ("network fault", e );
} Finally {
If (url_con! = NULL ){
Url_con.disconnect ();
}
}
System. Out. println ("response:" + responsecontent );
Return responsecontent;
}