The code is as follows:
1 Packagecom.test;2 3 ImportJava.io.BufferedReader;4 ImportJava.io.InputStream;5 ImportJava.io.InputStreamReader;6 7 ImportNet.sf.json.JSONObject;8 9 ImportOrg.apache.http.HttpResponse;Ten ImportOrg.apache.http.HttpStatus; One Importorg.apache.http.client.HttpClient; A ImportOrg.apache.http.client.methods.HttpPost; - Importorg.apache.http.entity.StringEntity; - Importorg.apache.http.impl.client.DefaultHttpClient; the ImportOrg.apache.http.message.BasicHeader; - ImportOrg.apache.http.protocol.HTTP; - - Public Abstract classTestsend { + - Public StaticString URL = "Http://115.28.191.62/web/control"; + A Public Static voidMain (string[] args) { at -Jsonobject jsobj1 =NewJsonobject (); -Jsonobject Jsobj2 =NewJsonobject (); -Jsobj2.put ("DeviceID", "112"); -Jsobj2.put ("channel", "channel"); -Jsobj2.put ("state", "0"); inJsobj1.put ("Item", jsobj2); -Jsobj1.put ("Requestcommand", "Control"); to + post (jsobj1); - the } * $ Public StaticString Post (jsonobject json) {Panax Notoginseng -HttpClient client =Newdefaulthttpclient (); theHttpPost post =NewHttpPost (URL); + APost.setheader ("Content-type", "Application/json"); thePost.addheader ("Authorization", "Basic YWRtaW46"); +String result = ""; - $ Try { $ -stringentity s =NewStringentity (Json.tostring (), "Utf-8"); -S.setcontentencoding (NewBasicheader (HTTP. Content_Type, the"Application/json")); - post.setentity (s);Wuyi the //Send Request -HttpResponse HttpResponse =Client.execute (POST); Wu - //Get response input stream AboutInputStream instream =httpresponse.getentity (). getcontent (); $BufferedReader reader =NewBufferedReader (NewInputStreamReader ( -Instream, "Utf-8")); -StringBuilder Strber =NewStringBuilder (); -String line =NULL; A while(line = Reader.readline ())! =NULL) +Strber.append (line + "\ n")); the instream.close (); - $result =strber.tostring (); the System.out.println (result); the the if(Httpresponse.getstatusline (). Getstatuscode () = =HTTPSTATUS.SC_OK) { the -SYSTEM.OUT.PRINTLN ("Request server succeeds, do the corresponding processing"); in the}Else { the AboutSYSTEM.OUT.PRINTLN ("Request Server failed"); the the } the + -}Catch(Exception e) { theSYSTEM.OUT.PRINTLN ("Request Exception");Bayi Throw NewRuntimeException (e); the } the - returnresult; - } the the}
Test receive
1 <%@ Page Language="Java"Import="java.util.*,java.io.*"pageencoding="UTF-8"%>2 <%3 4 System.out.println ("conenction Server success!");5 6 System.out.println (Request.getmethod ());7 8 //background Receive9 InputStreamReader Reader=NewInputStreamReader (Request.getinputstream (),"UTF-8");Ten Char [] Buff=Newchar[1024x768]; One intlength=0; A while((Length=reader.read (Buff))!=-1){ - - Stringx=New String(Buff,0, length); the - System.out.println (x); - } - + - //Response + Out.println ("{' Responsecommand ': ' 0 ', ' requestcommand ': ' Control '}"); A at %>
Java background send POST request, data transfer format JSON