Implementing this method requires importing some jar packages
can go to address download:
http://pan.baidu.com/s/1hqrJF7m
/**
* Utility class to get server resources
*
* Get method to transfer data
*
* 1. Set the transmission mode via path
* 2. Create client
* 3. Get input stream
* 4, read stream preparation work
* 5, Read and write
* @throws IOException
* @throws clientprotocolexception
*
*/
1 Public StaticString Gethttpresult (String path)throwsclientprotocolexception, ioexception{2 /*1. Set the transmission mode via path*/3 4HttpGet get=Newhttpget (path);5 /*2. Create Client*/6HttpClient client=Newdefaulthttpclient ();7 //send data to the server by means of get8HttpResponse response=Client.execute (get);9 /*3. Get input stream*/Ten if(Response.getstatusline (). Getstatuscode () ==200){ OneInputStream in=response.getentity (). getcontent (); A - /*4. Read the Flow preparation work*/ -Bytearrayoutputstream bos=NewBytearrayoutputstream (); the byte[]arr=New byte[1024]; - intLen=0; - - /*5. Read and write*/ + while(Len=in.read (arr))!=-1){ -Bos.write (arr, 0, Len); + } A byte[]b=Bos.tobytearray (); at return NewString (b,0, b.length); - } - - - - return NULL; in}
/**
* Utility class to get server resources
*
* Post method transmits data
*
* 1. Set the transmission mode via path
* 2. Create client
* 3. Get input stream
* 4, read stream preparation work
* 5, Read and write
* @throws IOException
* @throws clientprotocolexception
*
*/
1 Public StaticString Gethttpresult (String path)throwsclientprotocolexception, ioexception{2 /*0. Initialize the data to be sent with the list store*/3List<namevaluepair> list=NewArraylist<namevaluepair>();4List.add (NewBasicnamevaluepair ("name", "Zhangsan"));5List.add (NewBasicnamevaluepair ("name", "Lisi"));6List.add (NewBasicnamevaluepair ("name", "Wangwu"));7 /*1. Set the transmission mode via path*/8 9HttpPost post=Newhttppost (path);Ten /*2. Create Client*/ OneHttpClient client=Newdefaulthttpclient (); A //send data to the server via post form - - //Create a form theUrlencodedformentity entity=NewUrlencodedformentity (list, "Utf-8"); - //loading into the post - post.setentity (entity); - +HttpResponse response=Client.execute (POST); - /*3. Get input stream*/ + if(Response.getstatusline (). Getstatuscode () ==200){ AInputStream in=response.getentity (). getcontent (); at - /*4. Read the Flow preparation work*/ -Bytearrayoutputstream bos=NewBytearrayoutputstream (); - byte[]arr=New byte[1024]; - intLen=0; - in /*5. Read and write*/ - while(Len=in.read (arr))!=-1){ toBos.write (arr, 0, Len); + } - byte[]b=Bos.tobytearray (); the return NewString (b,0, b.length); * } $ Panax Notoginseng - the return NULL; + } A
Java HTTP messaging Post and get two ways to get server resources through utility classes