http POST请求Java CouchDB
我在本地主机上有一个couchdb:5984。 对于Java,我使用以下命令发出GET请求:
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方法。一切正常。 现在我想做一个post请求来发送一个JSONObject,我必须做什么? 我已经尝试过使用相同的方法添加DataOutputStream,但出现了错误的内容类型
# 1 楼答案
基于this其他StackOverflow问题,您可以有一个关于如何使用Java通过HTTP发布数据的基本示例。在您的情况下,您只是忘记在请求中设置
'Content-type: application/json'
此外,还有一些Java库,可以让您在不知道的情况下查询CouchDB。示例:ektorp