Constructing the HTTP header
Private Static Final String url = "url"; Private Static Final String App_key = "KEY"; Private Static Final String Secret_key = "SECRET";
/** * Constructs basic auth Authentication Header information * @return */ private String GetHeader () { = App_key + ":" + Secret_key; byte [] Encodedauth = Base64.encodebase64 (Auth.getbytes (Charset.forname ("Us-ascii")); New String (Encodedauth); return authheader; }
Old way:
Private voidsend1 (Jpushobject pushobject) {closeablehttpclient client=Httpclients.createdefault (); HttpPost Post=NewHttpPost (URL); System.out.println ("Data to send" +json.tojsonstring (pushobject)); Stringentity myentity=NewStringentity (Json.tojsonstring (pushobject), Contenttype.application_json);//Constructing request DataPost.addheader ("Authorization", GetHeader ()); Post.setentity (myentity);//set the request bodyString responsecontent =NULL;//Response ContentCloseablehttpresponse response =NULL; Try{Response=Client.execute (POST); SYSTEM.OUT.PRINTLN (json.tojsonstring (response)); if(Response.getstatusline (). Getstatuscode () = = 200) {httpentity entity=response.getentity (); Responsecontent= Entityutils.tostring (Entity, "UTF-8"); } System.out.println ("Responsecontent:" +responsecontent); } Catch(clientprotocolexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } finally { Try { if(Response! =NULL) Response.close (); } Catch(IOException e) {e.printstacktrace (); } finally { Try { if(Client! =NULL) Client.close (); } Catch(IOException e) {e.printstacktrace (); } } } }
HttpClient Way
Public voidSend ()throwsclientprotocolexception, IOException {HttpClient HttpClient=httpclientbuilder.create (). build (); HttpPost HttpPost=basehttppost.buildhttpheader (URL); //set parameters for the requestList<namevaluepair> Nvps =NewArraylist<namevaluepair>(); Nvps.add (NewBasicnamevaluepair ("Fromaccid", Fromaccid)); Nvps.add (NewBasicnamevaluepair ("Toaccids", Toaccids)); Nvps.add (NewBasicnamevaluepair ("type", Msgtype)); Map<string, object> BODY =NewHashmap<string, object>(); Body.put ("MSG", MSG); Nvps.add (NewBasicnamevaluepair ("Body", json.tojsonstring (body))); Nvps.add (NewBasicnamevaluepair ("Pushcontent", msg)); Httppost.setentity (NewUrlencodedformentity (Nvps, "Utf-8")); //Execute RequestHttpResponse response =Httpclient.execute (HttpPost); //Print Execution ResultsSystem.out.println (Entityutils.tostring (Response.getentity (), "Utf-8")); }
Java sends HTTP POST requests with basic Auth authentication