我从http://www.androidhive.info/2014/01/how-to-create-rest-api-for-android-app-using-php-slim-and-mysql-day-23/使用Slim Framework构建Web服务
我从Chrome浏览器检查了API,并且一切正常。但是我不知道如何在Android应用程序上使用它。
我尝试这样做:
// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpPost httpPost = new HttpPost(MY_API_URL);
// Building post parameters
// key and value pair
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
nameValuePair.add(new BasicNameValuePair("name", "Name_"));
nameValuePair.add(new BasicNameValuePair("email", "[email protected]"));
nameValuePair.add(new BasicNameValuePair("password", "pass"));
// Url Encoding the POST parameters
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
// Making HTTP Request
try {
HttpResponse response = httpClient.execute(httpPost);
// writing response to log
Log.d("Http Response:", response.toString());
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
怎么了?
最佳答案
我会使用retrofit而不是DefaultHTTPClient
。