Android Http request ClientProtocolException

2019-08-28 20:36发布

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

2条回答
Deceive 欺骗
2楼-- · 2019-08-28 20:52

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);
查看更多
SAY GOODBYE
3楼-- · 2019-08-28 21:01

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.

查看更多
登录 后发表回答