【发布时间】:2016-06-02 19:03:39
【问题描述】:
我真的很困惑,我正在尝试开发一个简单的功能,允许我从服务器发送和接收数据。
操作如下:
在我对服务器上的 PHP 文件执行 HTTP POST 的活动中,“PHP 文件”获取我发送的数据(通常是字符串),并使用通过 http 发送的参数执行查询。
例子:
我的android应用发送一个带有这个值“PIPPO”的字符串,在PHP文件中有一个查询,例如:
$value = PIPPO /* 从安卓应用接收到的数据*/ 从字符中选择 * where(characters.name=".$value.")
附言所有数据使用JSON格式
问题是: 我一直使用一个函数(效果很好),但现在所有方法都已弃用,我找不到最新 API 方法的替代方法。
这是我的代码:
public class ReadServer extends Activity {
String result;
public String readserver(String id_data, String data){
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("myurl/queryMobile.php");
StringBuilder builder = new StringBuilder();
String json = "";
//Build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate(id_data, data);
//Convert JSONObject to JSON to String
json = jsonObject.toString();
//Set json to StringEntity
StringEntity se = new StringEntity(json);
//Set httpPost Entity
httpPost.setEntity(se);
//Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
//Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
//Receive response as inputStream
StatusLine statusLine = httpResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
//Convert input stream to string
AlertDialog.Builder alertDialog;
switch(statusCode){
case 200:
HttpEntity entity = httpResponse.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line="";
try{
while ((line = reader.readLine()) != null) {
builder.append(line);
result = builder.toString();
}
}catch(Exception e){
alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("400 Bad Request");
alertDialog.setMessage("Non è stato possibile soddisfare la tua richiesta, riprova più tardi.");
alertDialog.show();
}
break;
【问题讨论】:
-
发布您的整个代码和错误堆栈跟踪。
-
你可以使用okHttp library
标签: php android json http-post deprecated