HttpConnection simple learning

Source: Internet
Author: User

We sometimes use httpClient when calling a remote interface. Of course, we can also use a class that comes with java to perform this operation. Here is a simple example:


Package com. hanchao. test; import java. io. bufferedReader; import java. io. inputStream; import java. io. inputStreamReader; import java.net. httpURLConnection; import java.net. URL; import net. sf. json. JSONObject;/************************ @ author: han * @ version: 1.0 * @ created: *************************/public class TestHttpConnection1 {/***** interface ********************** @ author: han * 2013-9 -23 ********************* @ param url * @ return * @ throws Exception */public static String getData (string urlStr) throws Exception {System. out. println ("=========== HttpConnectionUtil connection address:" + urlStr); StringBuffer answer = new StringBuffer (); InputStream is = null; inputStreamReader isr = null; BufferedReader br = null; try {if (urlStr = null | urlStr. equals ("") {return "";} URL = new URL (urlStr);/*** url. openConnection () * returns a URLConnection object, which indicates the connection to the remote object referenced by the URL. Each time the openConnection method of the protocol handler that calls this URL opens a new connection. */HttpURLConnection connection = (HttpURLConnection) url. openConnection ();/*** set the read timeout value to the specified timeout value, in milliseconds. Use a non-zero value to specify the timeout value for reading data from the Input stream after the connection to the resource is established. * If the timeout period expires before the data can be read, a java.net. SocketTimeoutException is triggered. Zero timeout indicates an infinite timeout. Some non-standard implementations of this method will ignore the specified timeout. To view the read timeout settings, call getReadTimeout (). */Connection. setReadTimeout (30000); // sets the URL request method connection. setRequestMethod ("GET");/*** sets a specified timeout value in milliseconds. This value is used when the communication link of the resource referenced by this URLConnection is opened. * If the timeout period expires before the connection is established, a java.net. SocketTimeoutException is triggered. Zero timeout indicates an infinite timeout. Some non-standard implementations of this method may ignore the specified timeout. To view the connection timeout settings, call getConnectTimeout (). */Connection. setConnectTimeout (30000);/*** set the doOutput field value of this URLConnection to the specified value. URL connections can be used for input and/or output. If you want to use a URL Connection for output, set the DoOutput flag to true. If you do not want to use it, set it to false. The default value is false */connection. setDoOutput (true);/*** open the communication link of the resource referenced in this URL if such a connection has not been established ). If the value of the connected field is true when the connection is enabled, the call is ignored. The URLConnection object goes through two stages: Create an object and establish a connection. After creating an object, you can specify various options such as doInput and UseCaches before establishing a connection ). An error occurs when you set the connection. Operations that can be performed only after connection, such as getContentLength), are implicitly connected if necessary. */Connection. connect (); is = connection. getInputStream (); isr = new InputStreamReader (is, "UTF-8"); br = new BufferedReader (isr); if (br! = Null) {/* String readString = null; while (readString = br. readLine ())! = Null) {answer. append (readString) ;}*/for (String oneline = null; (oneline = br. readLine ())! = Null; answer. append ("\ n") {System. out. println ("==================:" + oneline + "\ n"); answer. append (oneline) ;}} connection. disconnect (); System. out. println ("=========== HttpConnectionUtil disconnected =========");} catch (Exception e) {System. out. println ("===================== connection timeout .... "); E. printStackTrace () ;}finally {if (br! = Null) {try {br. close ();} catch (Exception e) {e. printStackTrace () ;}} return answer. toString (). trim ();}/*** test the main method ************************* @ author: han * 2013-9-24 ********************** @ param args */public static void main (String [] args) {String str = null; try {/*** test1 * // str = getData ("http://www.baidu.com "); /*** test2 * // str = getData ("http: // localhost: 8080/httpCli Ent/ajax. jspx? Type = car ");/*** test3 */str = getData (" http: // localhost: 8080/httpClient/ajax. jspx? Type = json "); // str is the json string JSONObject json = JSONObject. fromObject (str); System. out. println ("========= jsonResult:" + ", key1:" + json. get ("key1") + ", key2:" + json. get ("key2") + ", key3:" + json. get ("key3"); System. out. println ("--------------- result:" + str);} catch (Exception e) {e. printStackTrace ();}}}


Download example: httpConnection

This article is from the "My JAVA World" blog, please be sure to keep this source http://hanchaohan.blog.51cto.com/2996417/1301189

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.