我正在做一个Android应用程序,我在针对自己的服务器执行请求时遇到问题。我用Play Framework制作了服务器,然后从Json获取参数:
response.setContentTypeIfNotSet("application/json; charset=utf-8");
JsonParser jsonParser = new JsonParser();
JsonElement jsonElement = jsonParser.parse(getBody(request.body));
Long id =jsonElement.getAsJsonObject().get("id").getAsLong();
当我对我的服务器发出GET请求时,一切正常。但是,当我发出POST请求时,我的服务器返回一个未知错误,有关JSON格式不正确或者无法找到该元素的信息。
private ArrayList NameValuePair> PARAMS;
private ArrayList NameValuePair>头;
...
案例POST:
HttpPost postRequest = new HttpPost(host); // Add headers for(NameValuePair h : headers) { postRequest.addHeader(h.getName(), h.getValue()); } if(!params.isEmpty()) { postRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); } executeRequest(postRequest, host); break;
我已尝试处理请求的参数,但这是失败的:
如果(!params.isEmpty()) {
HttpParams HttpParams = new BasicHttpParams();for (NameValuePair param : params) { HttpParams.setParameter(param.getName(), param.getValue()); } postRequest.setParams(HttpParams); }
并且存在不同的错误,取决于我的要求。所有这些都是'play.exceptions.JavaExecutionException':
我希望有人可以帮助我。
答案 0 :(得分:3)
这是发送HTTP Post的简单方法。
HttpPost httppost = new HttpPost("Your URL here");
httppost.setEntity(new StringEntity(paramsJson));
httppost.addHeader("content-type", "application/json");
HttpResponse response = httpclient.execute(httppost);
最好直接使用JSON String,而不是在此解析它。希望它有所帮助
答案 1 :(得分:1)
Try this,It may help u
public void executeHttpPost(String string) throws Exception
{
//This method for HttpConnection
try
{
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost("URL");
List<NameValuePair> value=new ArrayList<NameValuePair>();
value.add(new BasicNameValuePair("Name",string));
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(value);
request.setEntity(entity);
client.execute(request);
System.out.println("after sending :"+request.toString());
}
catch(Exception e) {System.out.println("Exp="+e);
}
}