加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 使用6.0 API(Android)从服务器发送和接收数据

发布时间:2020-12-13 16:03:55 所属栏目:PHP教程 来源:网络整理
导读:我真的很困惑,我正在尝试开发一个简单的功能,允许我从服务器发送和接收数据. 操作如下: 在一个活动中,我对服务器上的PHP文件执行HTTP POST,“PHP文件”获取我发送的数据(通常是一个字符串),并使用通过http发送的参数执行查询. 例: 我的android应用程序发送
我真的很困惑,我正在尝试开发一个简单的功能,允许我从服务器发送和接收数据.

操作如下:

在一个活动中,我对服务器上的PHP文件执行HTTP POST,“PHP文件”获取我发送的数据(通常是一个字符串),并使用通过http发送的参数执行查询.

例:

我的android应用程序发送一个字符串,其值为“PIPPO”,在PHP文件中有一个查询,例如:

$value =从Android应用程序收到的PIPPO / *数据* /
从字符中选择*(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;

解决方法

试试这个代码.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读