java - How to specify OkHttp Client call correctly? -
java - How to specify OkHttp Client call correctly? -
i setup jetty server (v9.3.0.m0) simple jetty servlet writes httpservletrequest-body httpservletresponse follows:
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(); seek { string line; while ((line = reader.readline()) != null) { stringbuilder.append(line).append('\n'); } } { reader.close(); } string teststring = stringbuilder.tostring(); response.getwriter().println(teststring); } }
when specify , run jettycient (v9.3.0.m0) much this:
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 test".getbytes()), "text/plain") .send(); system.out.println(response.getcontentasstring()); client.stop(); } }
it runs perfectly, i.e. server responds intended , writes out "this test".
when specify okhttpclient (v2.0.0) much this:
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 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()); } }
i end empty body. seems body not arrive @ server. miss of import here?
try response.body().string()
, not response.body().to string()
.
java jetty okhttp jetty-9
Comments
Post a Comment