Http Put Request

2019-01-29 10:46发布

问题:

I am using the HttpPut to communicate with server in Android, the response code I am getting is 500.After talking with the server guy he said prepare the string like below and send.

{"key":"value","key":"value"}

now I am completely confused that where should i add this string in my request.

Please help me out .

回答1:

I recently had to figure out a way to get my android app to communicate with a WCF service and update a particular record. At first this was really giving me a hard time figuring it out, mainly due to me not knowing enough about HTTP protocols, but I was able to create a PUT by using the following:

    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();
    }

With this being said there is an easier option by using a library that will generate the update methods for you to allow for you to update a record without having to manually write the code like I did above. The 2 libraries that seem to be common are odata4j and restlet. Although I haven't been able to find a clear easy tutorial for odata4j there is one for restlet that is really nice: http://weblogs.asp.net/uruit/archive/2011/09/13/accessing-odata-from-android-using-restlet.aspx?CommentPosted=true#commentmessage



回答2:

Error 500 is Internal Server error. Not sure if this answers your question but I personally encountered it when trying to send a data URI for an animated gif in a PUT request formatted in JSON but the data URI was too long. You may be sending too much information at once.