2016-10-21 93 views
1

我在localhost上有一個couchdb:5984。 在Java我使用這個命令使一個GET請求:POST請求Java CouchDB

import java.io.BufferedOutputStream; 
import java.io.BufferedReader; 
import java.io.DataOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.io.PrintWriter; 
import java.net.Socket; 
import java.util.Enumeration; 
import java.util.Hashtable; 

public class Request { 

    private String host = ""; 
    private int port = 80; 
    private String path = ""; 
    private String method = "GET"; 
    private String body = ""; 
    private Hashtable headers = new Hashtable(); 

    /** 
    * Creates a new instance of HTTPClient 
    */ 
    public Request() { 
    } 

    public void setHost(String host, int port, String path) { 
     this.host = host; 
     this.port = port; 
     this.path = path; 
    } 

    public void setMethod(String method) { 
     this.method = method; 
    } 

    public void setBody(String body) { 
     this.body = body; 
    } 

    public void addRequestHeader(String key, String value) { 
     headers.put(key, value); 
    } 

    /** 
    * returns 2 strings String[0] is the request String[1] is the response 
    */ 
    public String[] send() throws IOException { 

     String response = ""; 
     String request = ""; 

     // NETWORK STUFFS 
     Socket socket = new Socket(host, port); 
     PrintWriter out = new PrintWriter(socket.getOutputStream()); 
     BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 

     // crea la request 
     request += method + " " + path + " HTTP/1.0\r\n"; 

     // aggiungi headers 
     Enumeration keys = headers.keys(); 
     while (keys.hasMoreElements()) { 
      String key = (String) keys.nextElement(); 
      String value = (String) headers.get(key); 
      request += key + ": " + value + "\r\n"; 
     } 
     // controllo content-length, indispensabile per il POST 
     if (headers.get("Content-Length:") == null) { 
      request += "Content-Length: " + body.getBytes().length + "\r\n"; 
     } 

     // linea di fine headers 
     request += "\r\n"; 

     // aggiungo il body 
     request += body; 

     // invio 
     //System.out.println(request+"\n"); 
     out.print(request); 
     out.flush(); 

     String s; 
     while ((s = in.readLine()) != null) { 
      response += s + "\n"; 
      //System.out.println(s); 
     } 

     in.close(); 
     out.close(); 
     socket.close(); 

     String[] result = new String[2]; 
     result[0] = request; 
     result[1] = response; 

     return result; 
    } 
} 

我插入:主機,端口和方法類型(「GET」),我使用send方法在這個類。一切正常。 現在我想要發送一個JSONObject的發佈請求,我必須做什麼? 我已經嘗試添加一個DataOutputStream相同的方法,但我有一個錯誤的內容類型錯誤。

回答

0

基於this其他StackOverflow的問題,你可以有一個關於如何通過HTTP發佈數據與Java的基本示例。在你的情況下,你只是忘記在你的請求中設置'Content-type: application/json'

此外,還有一些Java庫可以讓您在不知情的情況下查詢CouchDB。例如:ektorp