Http Put请求

时间:2012-05-03 13:54:57

标签: android http http-put

我正在使用HttpPut与Android中的服务器进行通信,我得到的响应代码是500.在与服务器人交谈后,他说准备下面的字符串并发送。

{ “键”: “值”, “关键”: “值”}

现在我完全感到困惑,我应该在我的请求中添加此字符串。

请帮帮我。

2 个答案:

答案 0 :(得分:8)

我最近不得不想办法让我的Android应用程序与WCF服务进行通信并更新特定记录。起初这真的让我很难搞清楚,主要是因为我对HTTP协议知之甚少,但我能够通过使用以下内容创建PUT

    URL url = new URL("http://(...your service...).svc/(...your table name...)(...ID of record trying to update...)");

    //--This code works for updating a record from the feed--
    HttpPut httpPut = new HttpPut(url.toString());
    JSONStringer json = new JSONStringer()
    .object() 
       .key("your tables column name...").value("...updated value...")
    .endObject();

    StringEntity entity = new StringEntity(json.toString());
    entity.setContentType("application/json;charset=UTF-8");//text/plain;charset=UTF-8
    entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
    httpPut.setEntity(entity); 

    // Send request to WCF service 
    DefaultHttpClient httpClient = new DefaultHttpClient();

    HttpResponse response = httpClient.execute(httpPut);                     
    HttpEntity entity1 = response.getEntity(); 

    if(entity1 != null&&(response.getStatusLine().getStatusCode()==201||response.getStatusLine().getStatusCode()==200))
    {
         //--just so that you can view the response, this is optional--
         int sc = response.getStatusLine().getStatusCode();
         String sl = response.getStatusLine().getReasonPhrase();
    }
    else
    {
         int sc = response.getStatusLine().getStatusCode();
         String sl = response.getStatusLine().getReasonPhrase();
    }

有了这个说法有一个更容易的选择,通过使用一个库,它将为您生成更新方法,允许您更新记录,而无需像我上面那样手动编写代码。似乎很常见的2个库是odata4jrestlet。虽然我无法为odata4j找到一个简单明了的简单教程,但restlet有一个非常好的教程:http://weblogs.asp.net/uruit/archive/2011/09/13/accessing-odata-from-android-using-restlet.aspx?CommentPosted=true#commentmessage

答案 1 :(得分:1)

错误500是内部服务器错误。 不确定这是否能回答您的问题,但是在尝试以JSON格式的PUT请求中发送动画gif的数据URI时,我亲自遇到了它,但是数据URI太长。您可能一次发送了太多信息。