Package junit;
Import java. io. InputStream;
Import java.net. HttpURLConnection;
Import java.net. URL;
Import org. junit. Test;
Import com. hrtx. util. StreamTool;
Public class EsmTest {
/**
* Simulate post form submission through HttpURLConnection
* @ Throws Exception
*/
@ Test
Public void sendEms () throws Exception {
String wen = "MS2201828 ";
String btnSearch = "EMS express query ";
URL url = new URL ("http://www.kd185.com/ EMS .php ");
HttpURLConnection conn = (HttpURLConnection) url. openConnection ();
Conn. setRequestMethod ("POST"); // submit Mode
// Conn. setConnectTimeout (10000); // connection timeout unit: milliseconds
// Conn. setReadTimeout (2000); // read timeout in milliseconds
Conn. setDoOutput (true); // whether the parameter is input
StringBuffer params = new StringBuffer ();
// Form parameters are the same as get parameters.
Params. append ("wen"). append ("="). append (wen). append ("&")
. Append ("btnSearch"). append ("="). append (btnSearch );
Byte [] bypes = params. toString (). getBytes ();
Conn. getOutputStream (). write (bypes); // enter the Parameter
InputStream inStream = conn. getInputStream ();
System. out. println (new String (StreamTool. readInputStream (inStream), "gbk "));
}
}
Encapsulated code:
/**
* Simulate post form submission through HttpURLConnection
*
* @ Param path
* @ Param params for example, "name = zhangsan & age = 21"
* @ Return
* @ Throws Exception
*/
Public static byte [] sendPostRequestByForm (String path, String params) throws Exception {
URL url = new URL (path );
HttpURLConnection conn = (HttpURLConnection) url. openConnection ();
Conn. setRequestMethod ("POST"); // submit Mode
// Conn. setConnectTimeout (10000); // connection timeout unit: milliseconds
// Conn. setReadTimeout (2000); // read timeout in milliseconds
Conn. setDoOutput (true); // whether the parameter is input
Byte [] bypes = params. toString (). getBytes ();
Conn. getOutputStream (). write (bypes); // enter the Parameter
InputStream inStream = conn. getInputStream ();
Return StreamTool. readInputStream (inStream );
}
Package com. hrtx. util;
Import java. io. ByteArrayOutputStream;
Import java. io. InputStream;
Public class StreamTool {
/**
* Read data from the input stream
* @ Param inStream
* @ Return
* @ Throws Exception
*/
Public static byte [] readInputStream (InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream ();
Byte [] buffer = new byte [1024];
Int len = 0;
While (len = inStream. read (buffer ))! =-1 ){
OutStream. write (buffer, 0, len );
}
Byte [] data = outStream. toByteArray (); // binary data of the webpage
OutStream. close ();
InStream. close ();
Return data;
}
}