-2

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

这是请求的样子:

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

我们如何有效地解析这个?

4

3 回答 3

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

}
于 2013-07-03T00:37:30.823 回答
0

为了更好地解析这个:

  • 首先,您似乎正在接受“原始”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 等,但如果你打算这样做,我认为这是不那么糟糕的解决方案。

于 2013-07-03T00:19:46.997 回答
0

您可以使用

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

或者

String json = request.getReader().readLine();
gson().fromJson(json, Event.class);
于 2014-01-15T17:44:31.823 回答