Android Http request ClientProtocolException

早过忘川 提交于 2019-12-13 05:16:14

问题


I have an API that seems to be working perfect when I test it using Firefox's "REST Client" or Google Chrome's "Simple REST Client" However, when I send an Http request using Android SDK I get the following exception:

ClientProtocolException: the server failed to respond with a valid HTTP response

also when I test using Google Chrome's "Advanced REST client" I got an empty response, so any idea about what might be causing this ?

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = null;
HttpPost httpPost = new HttpPost(Constants.URL);
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "application/json");
StringEntity se = new StringEntity(params,HTTP.UTF_8);
httpPost.setEntity(se);
httpClient.execute(httpPost);


回答1:


Your code seems to be correct.

ClientProtocolException happens if there is an INVALID REQUEST from the client or an INVALID RESPONSE from the server

Also you have specified httpPost.setHeader("Accept", "application/json"); it expects that the server is returning an JSON response. See docs for more details.

So you may check what response you are sending from the server. It should be a JSON response.

Or you can try removing httpPost.setHeader("Accept", "application/json"); and check what response you are getting.




回答2:


This should work

HttpParams httpParams=new BasicHttpParams();
DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
HttpResponse httpResponse = null;
HttpPost httpPost = new HttpPost(Constants.URL);
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "application/json");
StringEntity se = new StringEntity(params,HTTP.UTF_8);
httpPost.setEntity(se);
httpClient.execute(httpPost);


来源:https://stackoverflow.com/questions/18296451/android-http-request-clientprotocolexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!