java 发送带Basic Auth认证的http post请求实例代码
程序员文章站
2024-03-12 15:15:44
构造http header
private static final string url = "url";
private static final stri...
构造http header
private static final string url = "url"; private static final string app_key = "key"; private static final string secret_key = "secret";
/** * 构造basic auth认证头信息 * * @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; }
老方式:
private void send1(jpushobject pushobject) { closeablehttpclient client = httpclients.createdefault(); httppost post = new httppost(url); system.out.println("要发送的数据" + json.tojsonstring(pushobject)); stringentity myentity = new stringentity(json.tojsonstring(pushobject), contenttype.application_json);// 构造请求数据 post.addheader("authorization", getheader()); post.setentity(myentity);// 设置请求体 string responsecontent = null; // 响应内容 closeablehttpresponse 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方式
public void send() throws clientprotocolexception, ioexception { httpclient httpclient = httpclientbuilder.create().build(); httppost httppost = basehttppost.buildhttpheader(url); // 设置请求的参数 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(body))); nvps.add(new basicnamevaluepair("pushcontent", msg)); httppost.setentity(new urlencodedformentity(nvps, "utf-8")); // 执行请求 httpresponse response = httpclient.execute(httppost); // 打印执行结果 system.out.println(entityutils.tostring(response.getentity(), "utf-8")); }
以上这篇java 发送带basic auth认证的http post请求实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
下一篇: java定义数组的三种类型总结
推荐阅读