1

次のように、HttpServletRequest-body を HttpServletResponse に書き込む単純な Jetty サーブレットを使用して、Jetty サーバー (v9.3.0.M0) をセットアップします。

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());

    }
}

私は空の体で終わります。したがって、本体がサーバーに到着していないようです。ここで重要なことを見逃していますか?

4

1 に答える 1

0

Response.body().string()ではなく、試してみてくださいResponse.body().to string()

于 2014-11-07T13:17:25.397 に答える