Constructing HTTP Headers
Private static final String url = "url";
private static final String App_key = "KEY";
private static final String Secret_key = "SECRET";
/**
* Construction Basic Auth Authentication Header information
* *
@return
/private String GetHeader () {
string auth = App_key + ":" + Secret_key;
byte[] Encodedauth = Base64.encodebase64 (Auth.getbytes (Charset.forname ("Us-ascii"));
String Authheader = "Basic" + new String (Encodedauth);
return authheader;
}
Old way:
private void Send1 (Jpushobject pushobject) {closeablehttpclient client = Httpclients.createdefault ();
HttpPost post = new HttpPost (URL);
SYSTEM.OUT.PRINTLN ("Data to send" + json.tojsonstring (pushobject)); Stringentity myentity = new Stringentity (json.tojsonstring (pushobject), Contenttype.application_json);//construct request data post.
AddHeader ("Authorization", GetHeader ()); Post.setentity (myentity)//Set request body String responsecontent = null;
Response content Closeablehttpresponse response = null;
try {response = Client.execute (POST);
SYSTEM.OUT.PRINTLN (json.tojsonstring (response));
if (Response.getstatusline (). Getstatuscode () = = 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 Mode
public void Send () throws Clientprotocolexception, IOException {httpclient Httpclie
NT = Httpclientbuilder.create (). build ();
HttpPost httppost = basehttppost.buildhttpheader (URL);
Sets the requested parameter list<namevaluepair> Nvps = new arraylist<namevaluepair> ();
Nvps.add (New Basicnamevaluepair ("Fromaccid", Fromaccid));
Nvps.add (New Basicnamevaluepair ("Toaccids", Toaccids));
Nvps.add (New Basicnamevaluepair ("type", Msgtype));
map<string, object> BODY = new hashmap<string, object> ();
Body.put ("msg", MSG);
Nvps.add (New Basicnamevaluepair ("Body", json.tojsonstring));
Nvps.add (New Basicnamevaluepair ("Pushcontent", msg));
Httppost.setentity (New Urlencodedformentity (Nvps, "utf-8"));
Execution Request HttpResponse response = Httpclient.execute (HttpPost);
Print execution Results System.out.println (entityutils.tostring (Response.getentity (), "Utf-8")); }
Above this Java send with basic auth authentication HTTP POST request instance code is small series share to everybody's content, hope can give everybody a reference, also hope everybody support cloud habitat community.