我用一个简单的 Jetty Servlet 设置了一个 Jetty Server (v9.3.0.M0),它将 HttpServletRequest-body 写入 HttpServletResponse,如下所示:
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
public class SimpleServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
StringBuilder stringBuilder = new StringBuilder();
BufferedReader reader = request.getReader();
try {
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line).append('\n');
}
} finally {
reader.close();
}
String testString = stringBuilder.toString();
response.getWriter().println(testString);
}
}
当我像这样指定并运行 JettyCient (v9.3.0.M0) 时:
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.util.BytesContentProvider;
public class JettyClient {
public static void main(String[] args) throws Exception {
HttpClient client = new HttpClient();
client.start();
ContentResponse response = client.POST("http://localhost:8083/hello")
.content(new BytesContentProvider("this is a test".getBytes()), "text/plain")
.send();
System.out.println(response.getContentAsString());
client.stop();
}
}
它运行完美,即服务器按预期响应,它只是写出“这是一个测试”。
当我像这样指定 OkHttpClient (v2.0.0) 时:
import com.squareup.okhttp.*;
import java.io.IOException;
public class OkHttpClient {
public static void main(String[] args) throws IOException {
com.squareup.okhttp.OkHttpClient client = new com.squareup.okhttp.OkHttpClient();
RequestBody body = RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), "this is a test");
Request request = new Request.Builder()
.url("http://localhost:8083/hello")
.post(body)
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().toString());
}
}
我最终得到了一个空的身体。因此,似乎身体没有到达服务器。我在这里错过了一些重要的事情吗?