我试图将以下示例数组从php发布到java servlet:
$tags = $tagger->tag($nlquery);
$js_string = json_encode($tags);
echo $js_string
结果:
{"Example","NN"},{"1","NN"}
cUrl code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost:8080/first/SPARQL");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $js_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($js_string)));
curl_setopt($ch, CURLOPT_VERBOSE, 1);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
java servlet代码:
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
// TODO Auto-generated method stub
res.setContentType("text/html");
res.addHeader("Access-Control-Allow-Origin", "*");
PrintWriter out = res.getWriter();
String jsonData[];
jsonData= req.getParameterValues("js_string");
for(int i = 0; i < jsonData.length; i++)
{
System.out.println(jsonData[i]);
}
然而,这会在NullPointerException
行的java端产生jsonData.length
。我从PHP端传递$ js_string错了吗?或者他们的java端代码有问题吗?
更新:
使用以下代码:
BufferedReader br = new BufferedReader(new InputStreamReader (req.getInputStream()));
String str = br.readLine();
String[] jsondata = new String[]{str};
int i;
for(i=0; i < jsondata.length;i++){
System.out.println(jsondata[i]);
}
返回正确的结果{"Example","NN"},{"1","NN"}
但是,现在我无法遍历它,因为它没有将其视为多维数组。这是我在使用servlet之前使用的代码(静态,用于开发目的)
String[][] phpsearch ={{"Example","NN"},{"1","NN"}};
for(int i=0; i<phpsearch.length; i++) {
System.out.println("loop "+i);
if(phpsearch[i][1]=="NN"){
result=searchLabel(phpsearch[i][0].toLowerCase());
System.out.println("array "+phpsearch[i][0] );
}
}
可能不那么有效但至少它有效:
BufferedReader br = new BufferedReader(new InputStreamReader (req.getInputStream()));
String str = br.readLine();
str = str.replace(",", "|");
str = str.replace("}|{", ",");
str = str.replace("}", "");
str = str.replace("{", "");
String[] rows = str.split(",");
System.out.println("rows");
for(int i=0; i<rows.length; i++) {
System.out.println("loop "+i);
System.out.println(rows[i]);
//System.out.println(jsondata[i][1]);
}
String[][] jsondata = new String[rows.length][];
int r = 0;
for (String row : rows) {
jsondata[r++] = row.split("\\|");
}
System.out.println("jsondata");
for(int i=0; i<jsondata.length; i++) {
System.out.println("loop "+i);
System.out.println(jsondata[i][0]);
System.out.println(jsondata[i][1]);
//System.out.println(jsondata[i][1]);
}
产生二维数组,就像上面的静态例子一样。
答案 0 :(得分:0)
试试这个
BufferedReader br = new BufferedReader(new InputStreamReader (req.getInputStream()));
String str = br.readLine();
System.out.println(str);
// JSONObject data = new JSONObject(str);
这对我有用。