【问题标题】:How to extract JSON from this HTTP request in Java如何在 Java 中从此 HTTP 请求中提取 JSON
【发布时间】:2013-07-02 23:41:06
【问题描述】:

如果正确解析请求,下面的方法会被命中或错过......

请求如下所示:

POST /addEvent/ HTTP/1.1
Host: localhost:1234
Content-Type: multipart/form-data; boundary=Boundary+0xAbCdEfGbOuNdArY
Accept-Encoding: gzip, deflate
Content-Length: 201
Accept-Language: en;q=1, fr;q=0.9, de;q=0.8, ja;q=0.7, nl;q=0.6, it;q=0.5
Accept: application/json
Connection: keep-alive
User-Agent: XXXXXXXXXXXXXXXXXX

--Boundary+0xAbCdEfGbOuNdArY
Content-Disposition: form-data; name="userInfo"

{   "user_id" : 1,   "value" : "Water",   "typeCode" : "Searched" } 

这是我们现在提取它的方式...

//Key where the request begins
String keyString = "\"userInfo\"";

//Get the index of the key
int end = bufferedJson.lastIndexOf("\"userInfo\"");

//Create substring at beginning of the json
String json = bufferedJson.substring(end+keyString.length(), bufferedJson.length());

//Convert json to feed item
Gson gson = new Gson();
Event eventItem = gson.fromJson(json, Event.class);

我经常遇到这个错误:

Expected BEGIN_OBJECT but was STRING at line 1 column 1

我们怎样才能有效地解析这个?

【问题讨论】:

  • 如果它真的是一个 POST 请求,它不应该像那样全部放在一行上。
  • 我是网络新手……它是一个缓冲阅读器。
  • 基本上我只是想在userInfo之后得到所有东西
  • @waf 我刚刚在其他帖子中发现了更好、更强大的解决方案来获取 JSON 数据:stackoverflow.com/questions/3337056/…

标签: java gson


【解决方案1】:

使用Apache HTTP Client 4 以方便的方式读取 Http 响应正文。如果您需要将 json 进一步编组为 java 对象,请使用jackson。下面是示例代码:

import org.apache.http.client.ResponseHandler;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 * This example demonstrates the use of the {@link ResponseHandler} to simplify
 * the process of processing the HTTP response and releasing associated resources.
 */
public class ClientWithResponseHandler {

    public final static void main(String[] args) throws Exception {

        HttpClient httpclient = new DefaultHttpClient();
        try {
            HttpGet httpget = new HttpGet("http://www.google.com/");

            System.out.println("executing request " + httpget.getURI());

            // Create a response handler
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            // Body contains your json stirng
            String responseBody = httpclient.execute(httpget, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
            System.out.println("----------------------------------------");

        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }
    }

}

【讨论】:

    【解决方案2】:

    为了更好地解析这个:

    • 首先,您似乎正在接受“原始”HTTP POST 请求,然后使用 BufferedReader 逐行读取它(您的评论暗示了这一点),这样您将丢失新的行字符;如果你打算这样做,每次读取一行到你的最终字符串时都添加一个新行(“\n”),这样它就不会丢失新行,并有助于下一步的工作。

    • 现在,有了这个最终的字符串,您可以使用它:

      String json = null;
      
      Pattern pattern = Pattern.compile("\n\n");
      Matcher matcher = pattern.matcher(myString); // myString is the String you built from your header
      if(matcher.find() && matcher.find()) {
          json = myString.substring(matcher.start() + 2);
      } else {
          // Handle error: json string wasn't found
      }
      

    注意事项:在以下情况下有效:

    • POST 请求将始终是 multipart/form-data
    • 请求中没有其他参数
    • 一旦找到您的 json 数据,您就停止阅读请求
    • 正如我在第一步中所说,每次阅读一行时都包含“\n”

    我个人不会阅读原始 HTTP 标头,我宁愿使用 Apache commons FileUpload 等,但如果您打算这样做,我认为这是不那么糟糕的解决方案。

    【讨论】:

    • 你的回答能回答 OP 的问题吗?
    • @Junaid 它回答了帖子末尾的问题:“我们如何有效地解析这个?”
    • 听起来很有帮助。会试一试
    【解决方案3】:

    你可以使用

    gson().fromJson(request.getReader(), Event.class);
    

    String json = request.getReader().readLine();
    gson().fromJson(json, Event.class);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-26
      • 1970-01-01
      • 2011-05-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多