开发者

sending json object to HTTP server in android

I am sending a JSON object to a HTTP Server by using the following code.

The main thing is that I have to send Boolean values also.

public void getServerData() throws JSONException, ClientProtocolException, IOException {

    ArrayList<String> stringData = new ArrayList<String>();
    DefaultHttpClient httpClient = new DefaultHttpClient();
    ResponseHandler <String> resonseHandler = new BasicResponseHandler();
    HttpPost postMethod = new HttpPost("http://consulting.for-the.biz/TicketMasterDev/TicketService.svc/SaveCustomer");

    JSONObject json = new JSONObject();
    json.put("AlertEmail",true);
    json.put("APIKey","abc123456789");
    json.put("Id",0);
    json.put("Phone",number.getText().toString());
    json.put("Name",name.getText().toString());
    json.put("Email",email.getText().toString());
    json开发者_运维问答.put("AlertPhone",false);      
    postMethod.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
    String response = httpClient.execute(postMethod,resonseHandler);
    Log.e("response :", response);
    }

but its showing the exception in the line

String response = httpClient.execute(postMethod,resonseHandler);

as

org.apache.http.client.HttpResponseException: Bad Request

can any one help me.


The Bad Request is the server saying that it doesn't like something in your POST.

The only obvious problem that I can see is that you're not telling the server that you're sending it JSON, so you may need to set a Content-Type header to indicate that the body is application/json:

postMethod.setHeader( "Content-Type", "application/json" );

If that doesn't work, you may need to look at the server logs to see why it doesn't like your POST.

If you don't have direct access to the server logs, then you need to liaise with the owner of the server to try and debug things. It could be that the format of your JSON is slightly wrong, there's a required field missing, or some other such problem.

If you can't get access use to the owner of the server, the you could try using a packet sniffer, such as WireShark, to capture packets both from your app, and from a successful POST and compare the two to try and work out what is different. This can be a little bit like finding a needle in a haystack though, particularly for large bodies.

If you can't get an example of a successful POST, then you're pretty well stuffed, as you have no point of reference.


This may be non-technical, but String response = httpClient.execute(postMethod,-->resonseHandler); There is a spelling mistake in variable name here, use responseHandler(defined above)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜