2016-03-20 14 views
0

Ich bin auf der Suche nach der folgenden Curl-Anfrage in einem Java-Code. Ich sehe, dass wir mit httpget Restdienste aufrufen können.Convert curl zu httpGet

Hier ist mein curl Befehl:

curl -XGET 'localhost:9200/indexname/status/_search' -d '{"_source": {"include": [ "field1", "name1" ]}, "query" : {"term": { "Date" :"2000-12-23T10:12:05" }}}' 

Wie kann ich diesen Befehl setzen in meinem HttpGet httpGetRequest = new HttpGet(....);

Bitte Beratung. Vielen Dank.

+0

Beispiele hier sind: http : //www.mkyong.com/java/apache-httpclient-examples/ – Sanj

Antwort

0

Die Kombination -X GET and -d führt dazu, dass Ihre Daten an die URL im Format "application/x-www-form-urlencoded" angehängt werden.

Daher schlage ich mit URLEncoder wie folgt:

String host = "localhost:9200/indexname/status/_search"; 
String data = "{\"_source\": {\"include\": [ \"field1\", \"name1\" ]}, \"query\" : {\"term\": { \"Date\" :\"2000-12-23T10:12:05\" }}}"; 
String url = host + "?" + URLEncoder.encode(data, "UTF-8"); 
0

Sie die HttpURLConnection nutzen könnten. Dieser Code ist ein Beispiel ich denke, es wird für Sie arbeiten:

public void get() throws IOException{ 
    //Create a URL object. 
    String url = "localhost:9200/indexname/status/_search"; 
    URL getURL = new URL(url); 

    //Establish a https connection with that URL. 
    HttpsURLConnection con = (HttpsURLConnection) getURL.openConnection(); 

    //Select the request method, in this case GET. 
    con.setRequestMethod("GET"); 

    con.setDoOutput(true); 
    DataOutputStream wr = new DataOutputStream(con.getOutputStream()); 

    String parameters = "{\"_source\": {\"include\": [ \"field1\", \"name1\" ]}, \"query\" : {\"term\": { \"Date\" :\"2000-12-23T10:12:05\" }}}"; 

    //Write the parameter into the Output Stream, flush the data and then close the stream. 
    wr.writeBytes(parameters); 
    wr.flush(); 
    wr.close(); 

    System.out.println("\nSending 'GET' request to URL : " + url); 
    int responseCode; 
    try { 
     responseCode = con.getResponseCode(); 
     System.out.println("Response Code : " + responseCode); 
    } catch (Exception e) { 
     System.out.println("Error: Connection problem."); 
    } 

    //Read the POST response. 
    InputStreamReader isr = new InputStreamReader(con.getInputStream()); 
    BufferedReader br = new BufferedReader(isr); 

    StringBuffer response = new StringBuffer(); 

    String inputLine; 
    while ((inputLine = br.readLine()) != null) { 
     //Save a line of the response. 
     response.append(inputLine + '\n'); 
    } 
    br.close(); 

    System.out.println(response.toString()); 
} 

Wenn das tut es arbeiten, weil ich die Parameter misstyped haben müssen, versuchen Sie es trotzdem