我想通过spring为android实现GET请求。我不知道怎么把json放在url中。网址是:
我要设置的 context.getString(R.string.url) + "services/promotions?limit=10&where={expiredAt:{$gte: \""+getCurrentDate()+"\"}}";
但请求失败并在logcat上出现此错误:
Syntax error in regexp pattern near index \Qhttp://baas.papata.ir/services/promotions?limit=1&where=\E({$gte: "2014-05-05T14:48:20Z")\Q}\^
有什么问题?
更新:我使用该网址的课程是:
public class GetPromotion extends AsyncTask<Void, Void, Promotion[]> {
private String SERVICE_ID = "5345345";
private String API_VERSION = "0.1.0";
private String url;
private String clientId;
private Context context;
private OnGetPromotion onGetPromotion;
public GetPromotion(Context context, String clientId){
url = context.getString(R.string.url) + "services/promotions?limit=10&where={expiredAt:{$gte: \""+getCurrentDate()+"\"}}";
this.clientId = clientId;
this.context = context;
}
@Override
protected Promotion[] doInBackground(Void... voids) {
try {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("firstParam", API_VERSION);
requestHeaders.add("secondParam", SERVICE_ID);
requestHeaders.add("Cache-Control", "no-cache");
requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "json")));
HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
RestTemplate restTemplate = new RestTemplate(true);
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
restTemplate.getMessageConverters().add(
new MappingJackson2HttpMessageConverter());
restTemplate.getMessageConverters().add(
new StringHttpMessageConverter());
ResponseEntity<Promotion[]> response = restTemplate
.exchange(url, HttpMethod.GET, requestEntity,
Promotion[].class);
return response.getBody();
} catch (Exception e)
return null;
}
}
@Override
protected void onPostExecute(Promotion[] result) {
super.onPostExecute(result);
onGetPromotion.getOnGetPromotion(result);
}
private String getCurrentDate() {
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
df.setTimeZone(tz);
return df.format(new Date());
}
}
答案 0 :(得分:3)
您需要将json编码为URL,然后与服务URL连接。您还需要使用"
引用密钥。
String json_to_url=URLEncoder.encode("{\"expiredAt\":{\"$gte\":\"" + getCurrentDate() + "\"}}", "utf-8");
String serviceURL=context.getString(R.string.url) + "services/promotions?limit=10&where="+ json_to_url;
更好的方法是使用POST
来提交数据GET