java 발송 Basic Auth 인증 http post 요청 실례 코드

구조 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"));
  }
이상의 이 자바가 Basic Auth 인증을 받은 httppost 요청 실례 코드를 보내는 것은 여러분께 공유하는 모든 내용입니다. 참고 부탁드리고 저희를 많이 사랑해 주십시오.

좋은 웹페이지 즐겨찾기