我是Java和客户端服务器编程的新手。
我正在使用嵌入式Jetty,我尝试将JSON字符串发送到某个地址(http://localhost:7070/json),然后在该地址中显示JSON字符串。
我尝试了以下代码,但我得到的只是null。
嵌入式Jetty代码:
public static void main(String[] args) throws Exception {
Server server = new Server(7070);
ServletContextHandler handler = new ServletContextHandler(server, "/json");
handler.addServlet(ExampleServlet.class, "/");
server.start();
}
发送Http POST的客户端功能:
public static void sendHttp(){
HttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead
try {
HttpPost request = new HttpPost("http://localhost:7070/json");
JSONObject object = new JSONObject();
try {
object.put("name", "MyName");
object.put("age", "26");
} catch (Exception ex) {
System.out.println("Error: " + ex.getMessage());
}
String message = object.toString();
request.setEntity(new StringEntity(message, "UTF8"));
request.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(request);
// handle response here...
}catch (Exception ex) {
// handle exception here
} finally {
}
}
和Servlet功能:
public class ExampleServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//System.out.println("test get\n");
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//System.out.println("test post\n");
PrintWriter out = resp.getWriter();
String json_str = req.getParameter("name");
out.print(json_str);
}
}
在运行嵌入式Jetty服务器代码后,我从测试类调用sendHttp()方法(如果这很重要)。
答案 0 :(得分:2)
您需要阅读原始请求正文,如下所示。将其放在doPost
servlet
方法中,以便从请求中阅读json
:
StringBuilder jsonBuff = new StringBuilder();
String line = null;
try {
BufferedReader reader = req.getReader();
while ((line = reader.readLine()) != null)
jsonBuff.append(line);
} catch (Exception e) { /*error*/ }
System.out.println("Request JSON string :" + jsonBuff.toString());
//write the response here by getting JSON from jasonBuff.toString()
try {
JSONObject jsonObject = JSONObject.fromObject(jb.toString());
out.print(jsonObject.get("name"));//writing output as you did
} catch (ParseException e) {
throw new IOException("Error parsing JSON ");
}
注意:只有当您的标题如下所示时,才能访问req.getParameter("name");
:
content type: "application/x-www-form-urlencoded"
与正常的html表单提交一样。
答案 1 :(得分:1)
要从Post请求中获取数据,您需要获取内容。试试这个:
String data = IOUtils.toString(req.getInputStream(), "UTF-8");
答案 2 :(得分:0)
我没有使用过jetty,但是我已经用这段代码做了类似的通信(PUT,而不是POST):
URL url = new URL(desturl);
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
huc.setRequestMethod("PUT");
byte[] postData = null;
int postDataLength;
huc.setDoOutput(true);
postData = data.getBytes( StandardCharsets.UTF_8 );
postDataLength = postData.length;
huc.setRequestProperty( "Content-Type", "application/json");
huc.setRequestProperty( "charset", "utf-8");
huc.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
huc.setUseCaches( false );
huc.connect();
huc.setConnectTimeout(10000);
DataOutputStream wr = new DataOutputStream( huc.getOutputStream());
wr.write( postData );
rd = new BufferedReader(new InputStreamReader(huc.getInputStream()));
retcode = huc.getResponseCode();
答案 3 :(得分:0)
这是我的代码,这很好用
String data = "";
StringBuilder builder = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
data = builder.toString();
JSONObject object = new JSONObject(data);
//or JSONArray array = new JSONArray(data); which ever the one you want
祝你好运.....