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> params;

プライベート 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

HTTPPostを送信する簡単な方法は次のとおりです。

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 に答える