我正在尝试为我的 Android 应用程序设置一个 PHP API 以与之交互,我的问题是发布数据似乎永远不会发布,而且我永远无法从给定的 URL 检索响应正文(HTML/TXT) .
我的代码
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
try {
HttpClient client = new DefaultHttpClient();
HttpPost clientpost = new HttpPost("http://192.168.1.129/updateMain.php");
try {
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("_id", "1"));
params.add(new BasicNameValuePair("job_name", "Test"));
clientpost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(clientpost);
String responseBody = EntityUtils.toString(response.getEntity());
} catch(Exception e)
{
Log.e("Error", e.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
如果我可以发布数据,那么我就可以将 JSON 发布到服务器并从服务器检索 JSON,从而克服我目前面临的最大障碍。
非常感谢任何帮助。
最佳答案
public String getResponse(String url, List<NameValuePair> nameValuePairs) {
url = url.replaceAll(" ", "%20");
String result = "ERROR";
Log.d("Pair", nameValuePairs.toString());
HttpClient httpclient = new DefaultHttpClient();
HttpParams http_params = httpclient.getParams();
http_params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
HttpConnectionParams.setConnectionTimeout(http_params, TIMEOUT);
HttpConnectionParams.setSoTimeout(http_params, TIMEOUT);
HttpResponse response = null;
try {
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
result = "ERROR";
} catch (IOException e) {
e.printStackTrace();
result = "ERROR";
}
try {
// Get hold of the response entity
HttpEntity entity = null;
if (response != null) {
entity = response.getEntity();
}
if (entity != null) {
InputStream inputStream = entity.getContent();
result = convertStreamToString(inputStream);
}
} catch (IOException e) {
result = "ERROR";
}
httpclient.getConnectionManager().shutdown();
return result;
}
将此方法与 AsyncTask 或后台线程一起使用
关于php - Android 和 PHP 创建 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32226832/