当前位置: 移动技术网 > IT编程>开发语言>Java > java 发送带Basic Auth认证的http post请求实例代码

java 发送带Basic Auth认证的http post请求实例代码

2019年07月22日  | 移动技术网IT编程  | 我要评论

a66t,1953年一分纸币价格,读书魂电子书网

构造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请求实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网