如何在 Java 中从此 HTTP 请求中提取 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17437526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to extract JSON from this HTTP request in Java
提问by William Falcon
The method below is hit or miss if it parses the request properly...
如果它正确解析请求,下面的方法就会命中或错过......
Here is what the request looks like:
这是请求的样子:
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" }
Here is how we are extracting it now...
这是我们现在提取它的方式......
//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);
I get this error pretty often:
我经常收到此错误:
Expected BEGIN_OBJECT but was STRING at line 1 column 1
How can we parse this efficiently?
我们如何有效地解析它?
回答by Juned Ahsan
Use Apache HTTP Client 4to read Http response body in a convenient way. If you need to marshall your json further to a java object then make use of Hymanson. Here is the sample code:
使用Apache HTTP Client 4以方便的方式读取 Http 响应正文。如果您需要将 json 进一步编组为 java 对象,请使用Hymanson。这是示例代码:
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();
}
}
}
回答by Diego Plentz
You can use
您可以使用
gson().fromJson(request.getReader(), Event.class);
or
或者
String json = request.getReader().readLine();
gson().fromJson(json, Event.class);
回答by morgano
To parse this better:
为了更好地解析这个:
First, it seems like you're taking a "raw" HTTP POST request, and then reading it line by line using BufferedReader(your comment suggests this), this way you'll lose the new line chars; if you are going to do so, add a new line ("\n") every time you read a line to your final String, this way it doesn't lose the new lines and facilitates the things for the next step.
Now, with this final String, you can use this:
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 }
首先,您似乎正在接受“原始”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 }
CAVEATS: this works if:
警告:这在以下情况下有效:
- POST Request will always be multipart/form-data
- There are not other parameters in the request
- you STOP reading the request as soon as you find your json data
- you included "\n" every time you read a line as I said in the first step
- POST 请求将始终是 multipart/form-data
- 请求中没有其他参数
- 一旦你找到你的 json 数据,你就停止阅读请求
- 正如我在第一步中所说的那样,每次阅读一行时都包含“\n”
Personally I wouldn't read the raw HTTP header, I'd rather use Apache commons FileUpload or the like, but if your are going to do it this way, I think this is the less terrible solution.
就我个人而言,我不会读取原始 HTTP 标头,我宁愿使用 Apache commons FileUpload 等,但如果您打算这样做,我认为这是不那么糟糕的解决方案。