The company wants to encapsulate its own product into a WebService platform, so it recently began to learn how to use Java to send Http request content. This section was previously written in PHP and used in most basic sockets and third-party plug-ins.
I learned two Java methods: java.net. URLConnection and HttpClient. Without in-depth research on efficiency, it is troublesome to use java.net. URLConnection, while HttpClient is more comfortable.
The code is as follows: |
Copy code |
Java.net. URLConnection method: Private static void urlConnectionPost (){ StringBuilder responseBuilder = null; BufferedReader reader = null; OutputStreamWriter wr = null; URL url; Try { Url = new URL (TEST_URL ); URLConnection conn = url. openConnection (); Conn. setDoOutput (true ); Conn. setConnectTimeout (1000*5 ); Wr = new OutputStreamWriter (conn. getOutputStream ()); Wr. write (""); Wr. flush (); // Get the response Reader = new BufferedReader (new InputStreamReader (conn . GetInputStream ())); ResponseBuilder = new StringBuilder (); String line = null; While (line = reader. readLine ())! = Null ){ ResponseBuilder. append (line + "n "); } Wr. close (); Reader. close (); System. out. println (responseBuilder. toString ()); } Catch (IOException e ){ // TODO Auto-generated catch block E. printStackTrace (); } } HttpClient method:
Private static void httpClientPost (){ HttpClient client = new DefaultHttpClient (); HttpPost post = new HttpPost (TEST_URL ); Try { ContentProducer cp = new ContentProducer (){ Public void writeTo (OutputStream outstream) throws IOException { Writer writer = new OutputStreamWriter (outstream, "UTF-8 "); Writer. write (""); Writer. flush (); } }; Post. setEntity (new EntityTemplate (cp )); HttpResponse response = client.exe cute (post ); System. out. println (EntityUtils. toString (response. getEntity ())); } Catch (ClientProtocolException e ){ // TODO Auto-generated catch block E. printStackTrace (); } Catch (IOException e ){ // TODO Auto-generated catch block E. printStackTrace (); } } |