问题
public class HTTPPoster {
public static HttpResponse doPost(String url, JSONObject c) throws ClientProtocolException, IOException
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
HttpEntity entity;
StringEntity s = new StringEntity(c.toString());
s.setContentEncoding((Header) new BasicHeader(HTTP.DEFAULT_CONTENT_CHARSET, "application/json"));
entity = s;
request.setEntity(entity);
HttpResponse response;
response = httpclient.execute(request);
return response;
}
}
This is the code but on response = http.client.execute(request)
doesn't get response. I couldn't find why.
回答1:
You should call the method asynchronously. Then it will work with the same code. Add these two lines of code to your project
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
and make minimum sdk version to 9
回答2:
You can check that if you are getting response from server or not by using following code :
HttpResponse response = httpClient1.execute(request);
Log.v("response code", response.getStatusLine()
.getStatusCode() + "");
If you get the value of response code as 200 then you are getting data from server and if the response code value >=300 then you have error at your server side.
回答3:
First of all try to change the return type to String
by doing these 2 steps
Change
public static HttpResponse doPost(String url, JSONObject c) throws ClientProtocolException, IOException
to
public static String doPost(String url, JSONObject c) throws ClientProtocolException, IOException
AND
Change
HttpResponse response;
to
String response;
Now check the response string? Is it still null?
回答4:
This is a permission issue.
Add this line <uses-permission android:name="android.permission.INTERNET" />
to your manifest file and rebuild.
来源:https://stackoverflow.com/questions/6939122/not-getting-response-response-httpclient-executerequest