我尝试使用Apache从我的班级进行REST调用。但是当我打印REST服务的响应时,它给出了400异常。请找到下面的代码,让我知道为使其正常工作所需进行的更改,
List<NameValuePair> pickup = new ArrayList<NameValuePair>();
ArrayList<HashMap> pickupItemList = new ArrayList<HashMap>();
String [] productIds = prop.getArray("vproductIDs");
String [] quantities = prop.getArray("vquantities");
String [] tprices = prop.getArray("vtprices");
String [] bprices = prop.getArray("vbprices");
HashMap pickupObjMap = new HashMap<String, Object>();
pickupObjMap.put("loyaltyId",prop.getString("loyaltyId"));
pickupObjMap.put("loyaltyFName",prop.getString("loyaltyFName"));
pickupObjMap.put("orderId",prop.getString("orderId"));
pickupObjMap.put("locationId",prop.getString("locationId"));
pickupObjMap.put("consignmentId",prop.getString("consignmentId"));
pickupObjMap.put("description",prop.getString("description"));
pickupObjMap.put("retailerId",prop.getString("retailerId"));
pickupObjMap.put("pickupType",Integer.parseInt(prop.getString("pickupType")));
pickupObjMap.put("email",prop.getString("email"));
pickupObjMap.put("loyaltyLName",prop.getString("loyaltyLName"));
pickupObjMap.put("status",prop.getString("status"));
for(int i=0; i<productIds.length ; i++){
HashMap map = new HashMap<String, Object>();
map.put("sku", productIds[i]);
map.put("quantity", Double.parseDouble(quantities[i]));
map.put("totalPrice", Double.parseDouble(tprices[i]));
map.put("basePrice", Double.parseDouble(bprices[i]));
pickupItemList.add(map);
}
pickup.add(new BasicNameValuePair("pickupItemList", pickupItemList.toString()));
pickup.add(new BasicNameValuePair("pickupObj", pickupObjMap.toString()));
pickup.add(new BasicNameValuePair("ovclid", prop.getString("ovclid")));
HttpPost httppost = new HttpPost("Target URL");
try {
httppost.setEntity(new UrlEncodedFormEntity(pickup));
httppost.setHeader("Content-Type", "application/json");
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
if (bufferedReader != null) {
int cp;
StringBuilder sb = new StringBuilder();
while ((cp = bufferedReader.read()) != -1) {
sb.append((char) cp);
}
System.out.println("String Response......."+sb);
bufferedReader.close();
}
System.out.println("Response......."+entity.getContent());
} catch (Exception e) {
e.printStackTrace();
}
以下是我进行REST调用时的响应。
Unexpected character ('p' (code 112)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
at [Source: org.glassfish.jersey.message.internal.EntityInputStream@175d5e8a; line: 1, column: 2]
答案 0 :(得分:0)
“POST”中出现意外字符“P”,看起来服务器返回html而不是json。你能查看服务器日志并查看任何异常吗?什么是返回类型 - 它应该是json
post.setHeader("Content-type", "application/json");
如果你正在使用glassfish,你可能偶然发现了这个错误https://netbeans.org/bugzilla/show_bug.cgi?id=231159