gpt4 book ai didi

java - POST 请求 Java CouchDB

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:26:03 24 4
gpt4 key购买 nike

我在 localhost:5984 上有一个 couchdb。对于 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”),并在此类中使用发送方法。一切正常。现在我想做一个 post 请求来发送一个 JSONObject,我必须做什么?我已经尝试使用相同的方法添加 DataOutputStream,但出现错误的内容类型错误。

最佳答案

基于 this其他 StackOverflow 问题,您可以有一个关于如何使用 Java 通过 HTTP 发布数据的基本示例。在您的情况下,您只是忘记了在请求中设置 'Content-type: application/json'

此外,还有一些 Java 库可让您在不知道的情况下查询 CouchDB。示例:ektorp

关于java - POST 请求 Java CouchDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40173703/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com