我设置了一个Jetty Server(v9.3.0.M0)和一个简单的Jetty Servlet,它将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());
}
}
我最后得到一个空身。因此,似乎身体没有到达服务器。 我想念一些重要的东西吗?
答案 0 :(得分:0)
尝试Response.body().string()
,而不是Response.body().to string()
。