1

我正在做一个 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 格式错误或无法找到该元素。

私有 ArrayList NameValuePair> 参数;

私有 ArrayList NameValuePair> 标头;

...

案例发布:

  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;

我试图处理请求的参数,但失败了:

if(!params.isEmpty()) {
HttpParams HttpParams = new BasicHttpParams();

 for (NameValuePair param : params)
 {
      HttpParams.setParameter(param.getName(), param.getValue());
 }                
 postRequest.setParams(HttpParams); }

并且有不同的错误,取决于我提出的要求。它们都是'play.exceptions.JavaExecutionException':

  • 'com.google.gson.stream.MalformedJsonException'
  • '这不是 JSON 对象'
  • '期望找到对象:“id”'

我希望有人能帮助我。

4

2 回答 2

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 字符串而不是在这里解析它。希望能帮助到你

于 2013-01-22T10:10:53.620 回答
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);
          }

 }
于 2013-01-22T10:12:32.963 回答