Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在java中构造curl-XHEAD请求_Java_Http_Url_Curl_<img Src="//i.stack.imgur.com/RUiNP.png" Height="16" Width="18" Alt="" Class="sponsor Tag Img">elasticsearch - Fatal编程技术网 elasticsearch,Java,Http,Url,Curl,elasticsearch" /> elasticsearch,Java,Http,Url,Curl,elasticsearch" />

如何在java中构造curl-XHEAD请求

如何在java中构造curl-XHEAD请求,java,http,url,curl,elasticsearch,Java,Http,Url,Curl,elasticsearch,我正在使用ElasticSearchJavaAPI并尝试进行curl调用,以确定索引中是否存在文档。是如何在命令行中完成的。从这里的帖子可以看出,我应该使用HttpURLConnection java类或ApacheHttpClient以java发送curl请求。 我的要求应该是: curl-i-XHEADhttp://localhost:9200/indexName/mappingName/docID 实际上,关于如何通过java发送curl请求,有很多问题,但答案并不是很清楚——因此我不确定

我正在使用ElasticSearchJavaAPI并尝试进行curl调用,以确定索引中是否存在文档。是如何在命令行中完成的。从这里的帖子可以看出,我应该使用HttpURLConnection java类或ApacheHttpClient以java发送curl请求。 我的要求应该是:

curl-i-XHEADhttp://localhost:9200/indexName/mappingName/docID

实际上,关于如何通过java发送curl请求,有很多问题,但答案并不是很清楚——因此我不确定如何为curl-head请求配置请求参数。到目前为止,我已经复制了Ashay的答案,但它不起作用

有没有人在elasticsearch的java API中发送curl调用并解释如何执行

这是我的代码,我得到的错误是“java.net.malformedurexception:无协议”


另外,这个索引的文档ID是URL,这就是为什么我需要对它们进行编码。另一方面,我不确定是否应该对完整的http请求进行编码。

下面的代码片段可能是一个起点

String serverName = "localhost";
String indexName = "index_name";
String mappingName = "mapping_name";
String docId = "FooBarId";

String username = "JohnDoe";
String password = "secret";

String requestURL = String.format("http://%s:9200/%s/%s/%s",
        serverName,
        indexName,
        mappingName,
        docId
);
System.out.println("requestURL: " + requestURL);

URL url = new URL(requestURL);
System.out.println("URL: " + url);

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("X-Requested-With", "Curl");
connection.setRequestMethod("HEAD");

String credentials = username + ":" + password;

Base64.Encoder encoder = Base64.getEncoder();
String basicAuth = "Basic " + encoder.encodeToString(credentials.getBytes());

connection.setRequestProperty("Authorization", basicAuth);

connection.getHeaderFields()
        .entrySet()
        .forEach((Entry<String, List<String>> t) -> {
            System.out.printf("%-20s : %s%n", t.getKey(), t.getValue());
        });
添加也许您可以尝试类似以下步骤的操作。根据你的需要修改它们。也许你可以跳过第一步

为某物编制索引

curl -XPUT "http://localhost:9200/books/book/1" -d'
{
    "title": "The Hitchhikers Guide to the Galaxy",
    "author": "Douglas Adams",
    "year": 1978
}'
从命令行查询它

curl -X GET http://localhost:9200/books/book/1
输出

{"_index":"books","_type":"book","_id":"1","_version":1,"found":true,"_source":
{
    "title": "The Hitchhikers Guide to the Galaxy",
    "author": "Douglas Adams",
    "year": 1978
}}
requestURL: http://localhost:9200/books/book/1
null                 : [HTTP/1.1 200 OK]
Content-Length       : [184]
Content-Type         : [application/json; charset=UTF-8]
{"_index":"books","_type":"book","_id":"1","_version":1,"found":true,"_source":
{
    "title": "The Hitchhikers Guide to the Galaxy",
    "author": "Douglas Adams",
    "year": 1978
}}
...
year  : 1978
author: Douglas Adams
title : The Hitchhikers Guide to the Galaxy
使用上述Java代码段进行查询

String serverName = "localhost";
String indexName = "books";
String mappingName = "book";
String docId = "1";
String requestURL = String.format("http://%s:9200/%s/%s/%s",
        serverName,
        indexName,
        mappingName,
        docId
);
System.out.println("requestURL: " + requestURL);
URL url = new URL(requestURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.getHeaderFields()
        .entrySet()
        .forEach((Entry<String, List<String>> t) -> {
            System.out.printf("%-20s : %s%n", t.getKey(), t.getValue());
        });
try (InputStream inputStream = connection.getInputStream()) {
    for (int i = inputStream.read(); i > -1; i = inputStream.read()) {
        System.out.print((char) i);
    }
}
该示例使用默认的elasticsearch安装

取决于你真正想要达到的目标。您最好使用elasticsearch
TransportClient

import java.net.InetAddress;
import org.elasticsearch.action.get.GetRequestBuilder;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;

public class GetDemo {

    public static void main(String[] args) throws Exception {
        InetAddress hostAddr = InetAddress.getByName("localhost");
        InetSocketTransportAddress socketAddr =
                new InetSocketTransportAddress(hostAddr, 9300);
        try (Client client = TransportClient.builder().build()
                .addTransportAddress(socketAddr)) {
            GetRequestBuilder request = client.prepareGet("books", "book", "1");
            GetResponse response = request.execute().actionGet();
            response.getSource()
                    .forEach((k, v) -> System.out.printf("%-6s: %s%n", k, v));
        }
    }
}
输出

{"_index":"books","_type":"book","_id":"1","_version":1,"found":true,"_source":
{
    "title": "The Hitchhikers Guide to the Galaxy",
    "author": "Douglas Adams",
    "year": 1978
}}
requestURL: http://localhost:9200/books/book/1
null                 : [HTTP/1.1 200 OK]
Content-Length       : [184]
Content-Type         : [application/json; charset=UTF-8]
{"_index":"books","_type":"book","_id":"1","_version":1,"found":true,"_source":
{
    "title": "The Hitchhikers Guide to the Galaxy",
    "author": "Douglas Adams",
    "year": 1978
}}
...
year  : 1978
author: Douglas Adams
title : The Hitchhikers Guide to the Galaxy

以下代码段可能是一个起点

String serverName = "localhost";
String indexName = "index_name";
String mappingName = "mapping_name";
String docId = "FooBarId";

String username = "JohnDoe";
String password = "secret";

String requestURL = String.format("http://%s:9200/%s/%s/%s",
        serverName,
        indexName,
        mappingName,
        docId
);
System.out.println("requestURL: " + requestURL);

URL url = new URL(requestURL);
System.out.println("URL: " + url);

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("X-Requested-With", "Curl");
connection.setRequestMethod("HEAD");

String credentials = username + ":" + password;

Base64.Encoder encoder = Base64.getEncoder();
String basicAuth = "Basic " + encoder.encodeToString(credentials.getBytes());

connection.setRequestProperty("Authorization", basicAuth);

connection.getHeaderFields()
        .entrySet()
        .forEach((Entry<String, List<String>> t) -> {
            System.out.printf("%-20s : %s%n", t.getKey(), t.getValue());
        });
添加也许您可以尝试类似以下步骤的操作。根据你的需要修改它们。也许你可以跳过第一步

为某物编制索引

curl -XPUT "http://localhost:9200/books/book/1" -d'
{
    "title": "The Hitchhikers Guide to the Galaxy",
    "author": "Douglas Adams",
    "year": 1978
}'
从命令行查询它

curl -X GET http://localhost:9200/books/book/1
输出

{"_index":"books","_type":"book","_id":"1","_version":1,"found":true,"_source":
{
    "title": "The Hitchhikers Guide to the Galaxy",
    "author": "Douglas Adams",
    "year": 1978
}}
requestURL: http://localhost:9200/books/book/1
null                 : [HTTP/1.1 200 OK]
Content-Length       : [184]
Content-Type         : [application/json; charset=UTF-8]
{"_index":"books","_type":"book","_id":"1","_version":1,"found":true,"_source":
{
    "title": "The Hitchhikers Guide to the Galaxy",
    "author": "Douglas Adams",
    "year": 1978
}}
...
year  : 1978
author: Douglas Adams
title : The Hitchhikers Guide to the Galaxy
使用上述Java代码段进行查询

String serverName = "localhost";
String indexName = "books";
String mappingName = "book";
String docId = "1";
String requestURL = String.format("http://%s:9200/%s/%s/%s",
        serverName,
        indexName,
        mappingName,
        docId
);
System.out.println("requestURL: " + requestURL);
URL url = new URL(requestURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.getHeaderFields()
        .entrySet()
        .forEach((Entry<String, List<String>> t) -> {
            System.out.printf("%-20s : %s%n", t.getKey(), t.getValue());
        });
try (InputStream inputStream = connection.getInputStream()) {
    for (int i = inputStream.read(); i > -1; i = inputStream.read()) {
        System.out.print((char) i);
    }
}
该示例使用默认的elasticsearch安装

取决于你真正想要达到的目标。您最好使用elasticsearch
TransportClient

import java.net.InetAddress;
import org.elasticsearch.action.get.GetRequestBuilder;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;

public class GetDemo {

    public static void main(String[] args) throws Exception {
        InetAddress hostAddr = InetAddress.getByName("localhost");
        InetSocketTransportAddress socketAddr =
                new InetSocketTransportAddress(hostAddr, 9300);
        try (Client client = TransportClient.builder().build()
                .addTransportAddress(socketAddr)) {
            GetRequestBuilder request = client.prepareGet("books", "book", "1");
            GetResponse response = request.execute().actionGet();
            response.getSource()
                    .forEach((k, v) -> System.out.printf("%-6s: %s%n", k, v));
        }
    }
}
输出

{"_index":"books","_type":"book","_id":"1","_version":1,"found":true,"_source":
{
    "title": "The Hitchhikers Guide to the Galaxy",
    "author": "Douglas Adams",
    "year": 1978
}}
requestURL: http://localhost:9200/books/book/1
null                 : [HTTP/1.1 200 OK]
Content-Length       : [184]
Content-Type         : [application/json; charset=UTF-8]
{"_index":"books","_type":"book","_id":"1","_version":1,"found":true,"_source":
{
    "title": "The Hitchhikers Guide to the Galaxy",
    "author": "Douglas Adams",
    "year": 1978
}}
...
year  : 1978
author: Douglas Adams
title : The Hitchhikers Guide to the Galaxy

谢谢你的回复。您的示例代码为所有docid生成一个“null=[HTTP/1.1400错误请求]内容长度=[145]内容类型=[text/plain;charset=UTF-8]”错误。我所做的唯一更改是用我们的服务器名替换localhost,并使用“Base64.encodeBase64(credentials.getBytes());”,因为Base64.Encoder是private@KonstantinaLazaridou是Java 8中的
公共静态类。您是否检查了生成的
url
basicAuth
?由于
HTTP 400
是用于
的,由于语法错误,服务器无法理解该请求。
是的,url看起来不错,用户信息也正确。服务器是否可能使用与Base64不同的加密系统?我还推荐了authorization属性(如果没有必要的话),但仍然是相同的错误。我也不知道
.setRequestProperty(“X-Requested-With”,“Curl”)语法正确。@请尝试分析问题。1) 输入要在浏览器中访问的url。a) url是否有效。b) 您是否获得用户/密码的请求弹出窗口。2) 如果url正在工作,请将其作为固定字符串分配给上例中的
requestURL
。另一个问题是您的curl示例在没有用户/密码的情况下工作?如果是的话。为什么您认为java代码中需要它?谢谢您的回复。您的示例代码为所有docid生成一个“null=[HTTP/1.1400错误请求]内容长度=[145]内容类型=[text/plain;charset=UTF-8]”错误。我所做的唯一更改是用我们的服务器名替换localhost,并使用“Base64.encodeBase64(credentials.getBytes());”,因为Base64.Encoder是private@KonstantinaLazaridou是Java 8中的
公共静态类。您是否检查了生成的
url
basicAuth
?由于
HTTP 400
是用于
的,由于语法错误,服务器无法理解该请求。
是的,url看起来不错,用户信息也正确。服务器是否可能使用与Base64不同的加密系统?我还推荐了authorization属性(如果没有必要的话),但仍然是相同的错误。我也不知道
.setRequestProperty(“X-Requested-With”,“Curl”)语法正确。@请尝试分析问题。1) 输入要在浏览器中访问的url。a) url是否有效。b) 您是否获得用户/密码的请求弹出窗口。2) 如果url正在工作,请将其作为固定字符串分配给上例中的
requestURL
。另一个问题是您的curl示例在没有用户/密码的情况下工作?如果是的话。为什么您认为java代码中需要它?