2011-06-15 86 views
6

我用下面的代码发送JSON对象到HTTP服务器。发送JSON对象到HTTP服务器的android

最主要的是,我也送布尔值。

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

但其显示的例外行

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

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

任何一个可以帮助我。

+0

什么是'postMethod.setEntity(new ByteArrayEntity(json.toString()。getBytes(“UTF8”)));'for? – hwrdprkns 2011-06-15 14:18:40

回答

13

坏请求服务器说,它不喜欢在您的文章的东西。

,我可以看到的唯一明显的问题是,你不告诉你要发送它JSON的服务器,所以你可能需要设置Content-Type头,以指示身体application/json

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

如果不工作,你可能需要看看服务器日志,看看它为什么不喜欢你的文章。

如果您没有直接访问服务器日志,那么您需要联系服务器的所有者来尝试和调试东西。这可能是因为你的JSON格式有些不对,还有一个必填字段丢失或者其他一些问题。

如果您无法访问服务器的所有者,您可以尝试使用数据包嗅探器(例如WireShark)从您的应用程序和成功的POST捕获数据包,并将两者进行比较试着弄清楚什么是不同的。这可能有点像在干草堆里找到针,特别是对于大型身体。

如果你不能得到一个成功的POST的例子,那么你很好填充,因为你没有参考点。

+0

+1它为我工作。 – 2012-02-29 06:02:13

1

这可能是非技术性的,但是 String response = httpClient.execute(postMethod, - > resonseHandler); 这里有变量名拼写错误,使用responseHandler(上面定义)