【问题标题】:Custom Request Method in JAVAJAVA中的自定义请求方法
【发布时间】:2015-06-26 13:33:28
【问题描述】:

在将数据发布到服务器 URL 时,我一直在尝试在 HTTP 标头中实现自定义请求方法。 我的应用程序特定 URL 接受 -X 参数和 -d 数据。 基本上,我正在尝试使用运行正常的 CURL 命令将 JSON 数据转储到我的流入数据库中。但问题是,如果我用正确的方法在 java 中实现相同的功能,它就不受支持或无法正常工作。

我的 CURL 命令是:

curl -X POST -d 'my_json_data' 'my_url'

如何使用 HttpUrlConnection 或其他可用方法(即 Apache 客户端服务)在 java 中实现相同的功能。

【问题讨论】:

  • “自定义请求方法”是什么意思?你的 curl 命令是一个常规的 POST 请求。
  • 根据 CURL 文档, -X is "(HTTP) 指定与 HTTP 服务器通信时使用的自定义请求方法。将使用指定的请求而不是其他使用的方法(默认为GET). " 我的服务器使用 -X 选项和 -d 接受数据。
  • 您误解了 curl 文档。 -d 设置 http post 请求的数据,因此 curl 将自动创建 post 请求(如果已设置)。 -X 允许您将请求方法(即标头值)设置为不同的值。但是既然你把它设置为 POST 它当然仍然是一个 post 请求。
  • “我的服务器使用 -X 选项和 -d 接受数据”是什么意思。我对你试图做这样的事情感到不好:http://my_url?X=POST&d=my_json_data
  • 没有。我要做的是 curl -X POST -d "mydata" "myurl" ,这是我需要遵循的格式,将我的 JSON 数据直接转储到 influxdb 中。

标签: java curl httprequest


【解决方案1】:

根据here提供的文档,您可以使用以下大纲来解决您的目的:

// Use URI builder to build the URL and connect to URL using HttpURLConnection
Uri uri = Uri.parse(BASE_URL).buildUpon().appendQueryParameter("d","my_json_data");

// Create the request to your API and open the connection
URL url = new URL(uri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.connect();

// Read input in string
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
    return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
    buffer.append(line + "\n");
}
if (buffer.length() == 0) {
    return null;
}
String response = buffer.toString();

我也会推荐你参加这个讨论:How to add parameters to HttpURLConnection using POST

【讨论】:

  • 我的连接格式是这样的——curl -X POST -d 'my_json_data' 'my_url'。无论如何,我需要保持这种精确的格式,因为我的服务器只会听这种精确的格式。需要发送 -X 和 -d 与标头。
猜你喜欢
  • 2017-06-11
  • 2022-12-06
  • 2019-04-06
  • 2016-12-05
  • 2012-04-22
  • 1970-01-01
  • 1970-01-01
  • 2017-02-01
  • 1970-01-01
相关资源
最近更新 更多