java - 如何在 java 中获取 http 的响应?

标签 java amazon-web-services http aws-lambda response

我使用以下代码创建了一个 http 请求:

public void sendPost(String body) {
    try {
HttpPost request = new HttpPost("https:url");
StringEntity params = new StringEntity("{}");

if (body.equalsIgnoreCase("")) {
    params = new StringEntity("{}");
}

request.addHeader("Token", "TokenValue");
request.addHeader("base64", body);
request.setEntity(params);
HttpResponse response = client.execute(request);
System.out.println(response);
    } catch (Exception e) {
System.out.println("Something isn't right! Error: " + e);
    }
}

我正在使用 AWS lambda 创建对 http.我该怎么做呢?我需要主课吗?如果不是,程序现在如何在哪里找到对 http 的响应?欢迎任何帮助,谢谢。

最佳答案

我不知道这是否是您正在寻找的内容,但我有这个客户端来使用 http 服务

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

public class NetClient {


  private String uri;
  private int timeout;
  private String method;
  private String accept;
  private Object entity;
  private int readTimeout;

  private Map<String, String> parameters;
  private Map<String, String> headerParameters;
  private Map<String, String> replaceParameters;
  private Map<String, String> requestProperties;

  private void init() {

    this.parameters = new HashMap<>();
    this.headerParameters = new HashMap<>();
    this.replaceParameters = new HashMap<>();
    this.requestProperties = new HashMap<>();

    if (this.method != null) {
      this.method = this.method.toUpperCase();
    }

    if (this.uri != null) {
      this.uri = this.uri.toLowerCase();
    }

  }

  public NetClient(String uri, String method) {

    this.uri = uri;
    this.method = method != null ? method.toUpperCase() : "GET";
    this.accept = "application/json";

    this.init();

  }

  public NetClient(String uri) {

    this.method = "GET";
    this.accept = "application/json";
    this.uri = uri;

    this.init();
  }

  public String consumeService() throws IOException {

    long transactionID = System.currentTimeMillis();

    StringBuilder builderUrl = new StringBuilder();
    builderUrl.append(this.uri);

    StringBuilder builderParameters = new StringBuilder();

    this.addParameters(builderUrl, builderParameters);

    if ((this.method != null) && this.method.equals("GET") && (this.parameters != null)
        && !this.parameters.isEmpty()) {
      builderUrl.append(builderParameters.toString());
    }

    URL url = new URL(builderUrl.toString());
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    conn.setRequestMethod(this.method);
    conn.setDoOutput(true);

    if (this.timeout > 0) {
      conn.setConnectTimeout(this.timeout);
    }

    if (this.readTimeout > 0) {
      conn.setReadTimeout(this.readTimeout);
    }

    // Headers
    this.addHeaders(transactionID, conn);

    // Send post request
    this.sendPostRequest(transactionID, builderParameters, conn);

    System.out.println("builderUrl: " + builderUrl);

    // Send json object
    if (this.entity != null) {

      conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
      conn.setRequestMethod(this.method);
      conn.setDoInput(true);
      conn.setDoOutput(true);

      ObjectMapper mapper = new ObjectMapper();

      String json = mapper.writeValueAsString(this.entity);

      conn.setFixedLengthStreamingMode(json.getBytes().length);
      try (OutputStream os = conn.getOutputStream()) {
        os.write(json.getBytes(java.nio.charset.StandardCharsets.UTF_8));
      }
    }

    // Validate reponse
    if ((conn.getResponseCode() != 200) && (conn.getResponseCode() != 201)) {
      throw new RuntimeException(
          "[NetClientException] " + conn.getResponseCode() + " " + conn.getResponseMessage());
    }

    InputStreamReader in = new InputStreamReader(conn.getInputStream());
    BufferedReader br = new BufferedReader(in);
    String output;
    StringBuilder sb = new StringBuilder();

    // Read response
    while ((output = br.readLine()) != null) {

      for (Map.Entry<String, String> entry : this.replaceParameters.entrySet()) {
        if ((output != null) && output.contains(entry.getKey())) {
          output = output.replace(entry.getKey(), entry.getValue());
        }
      }

      sb.append(output);
    }

    in.close();

    conn.disconnect();
    return sb.toString();

  }

  private void sendPostRequest(long transactionID, StringBuilder builderParameters,
      HttpURLConnection conn) throws IOException {
    if ((this.method != null) && this.method.equals("POST") && (this.parameters != null)
        && !this.parameters.isEmpty()) {
      try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
        wr.writeBytes(builderParameters.toString());
        wr.flush();
      }
    }
  }

  private void addHeaders(long transactionID, HttpURLConnection conn) {
    if ((this.headerParameters != null) && !this.headerParameters.isEmpty()) {
      for (Map.Entry<String, String> entry : this.headerParameters.entrySet()) {
        conn.setRequestProperty(entry.getKey(), entry.getValue());
      }
    }
  }

  private void addParameters(StringBuilder builderUrl, StringBuilder builderParameters)
      throws UnsupportedEncodingException {
    if ((this.parameters != null) && !this.parameters.isEmpty()) {

      builderUrl.append("?");

      int size = this.parameters.size();
      int counter = 0;

      for (Map.Entry<String, String> entry : this.parameters.entrySet()) {

        builderParameters.append(entry.getKey());
        builderParameters.append("=");
        builderParameters.append(URLEncoder.encode(entry.getValue(),
            java.nio.charset.StandardCharsets.UTF_8.displayName()));

        if (counter < (size - 1)) {
          builderParameters.append("&");
        }

        counter++;
      }

    }
  }

  public void addParameters(String key, String value) {
    this.parameters.put(key, value);
  }

  public void addHeaderParameters(String key, String value) {
    this.headerParameters.put(key, value);
  }

  public void addReplaceParameters(String key, String value) {
    this.replaceParameters.put(key, value);
  }

  public void addRequestProperties(String key, String value) {
    this.requestProperties.put(key, value);
  }

  public String getUri() {
    return this.uri;
  }

  public String getMethod() {
    return this.method;
  }

  public String getAccept() {
    return this.accept;
  }

  public Map<String, String> getParameters() {
    return this.parameters;
  }

  public Map<String, String> getHeaderParameters() {
    return this.headerParameters;
  }

  public Map<String, String> getReplaceParameters() {
    return this.replaceParameters;
  }

  public Map<String, String> getRequestProperties() {
    return this.requestProperties;
  }

  public void setEntity(Object entity) {
    this.entity = entity;
  }

  public int getTimeout() {
    return this.timeout;
  }

  public void setTimeout(int timeout) {
    this.timeout = timeout;
  }

  public int getReadTimeout() {
    return this.readTimeout;
  }

  public void setReadTimeout(int readTimeout) {
    this.readTimeout = readTimeout;
  }

  @Override
  public String toString() {
    return "NetClient{" + "uri=" + this.uri + ", method=" + this.method + ", accept=" + this.accept
        + ", entity=" + this.entity + ", timeout=" + this.timeout + ", readTimeout="
        + this.readTimeout + ", parameters=" + this.parameters + ", headerParameters="
        + this.headerParameters + ", replaceParameters=" + this.replaceParameters
        + ", requestProperties=" + this.requestProperties + '}';
  }

}

关于java - 如何在 java 中获取 http 的响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59522755/

相关文章:

java - WildFly 8.2 和 304 未修改

amazon-web-services - 跨两个不同的 AWS 账户将数据从 DynamoDB 复制到 Redshift 中?

json - 使用模板将 json 输出到 http.ResponseWriter

javascript - AngularJS XMLHttpRequest 无法加载 X。不存在 'Access-Control-Allow-Origin' header

amazon-web-services - Elastic Beanstalk : allow user to deploy

ruby-on-rails - RSpec::Core::ExampleGroup::Nested_2 中未定义的方法 `it'

java - 从外部类到 recyclerView 的 notifyDataSetChanged()

java - temp.compareTo 错误。 Int 不能被取消引用

java - RecyclerView 没有调用 onCreateViewHolder 或 onBindView

node.js - 在 AWS Lambda 函数中通过 AWS SES 发送电子邮件