Android:如何使用POST方法发送带有变量的json请求并从Web服务器读取json响应?

时间:2016-04-27 06:43:31

标签: android json

我是新手,任何机构都可以编写一个简单的代码,用于在以下网络服务器链接上发送json请求,其中包含变量" data"然后获取json响应,也给出了一个例子,我得到了这个信息

  

http://teespire.com/ptracking/post/index.php?tag=GetDeviceInfo

     

JSON请求(使用变量#34发布在主体中;数据")

     

{       "做了":" 1"   }

     

JSON响应

     

{       "状态":200,       " status_message":"成功",       "数据":{           "做了":" 1",           " displayname":" Malik Kamran",           " dtoken":" sdfhskdflkasjdfklajslkdfj",           " dtype":" ios",           " dateadded":" 2015-04-25 15:47:34 -0700",           "国家":"巴基斯坦",           "大陆":"亚洲",           " lat":" 123.46477",           " lng":" 123.46477"       }   }

1 个答案:

答案 0 :(得分:0)

从非ui线程调用以下方法并传递url和body内容。使用AsyncTask并在doInBackground方法中调用以下方法。

class BackgroundTask extends AsyncTask<Void,Void,String>{

        @Override
        protected String doInBackground(Void... voids) {

            String url  = "http://teespire.com/ptracking/post/index.php?tag=GetDeviceInfo";
            String body = "{ \"did\": \"1\" }";

            return excutePost(url,body);
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if(result != null){
                try {
                    JSONObject jsonObject = new JSONObject(result);

                    int status = jsonObject.getInt("status");
                    JSONObject dataObject = jsonObject.getJSONObject("data");
                    String displayName = dataObject.getString("displayname");


                    //do your stuff here

                }catch (JSONException e){
                    e.printStackTrace();
                }
            }
        }
    } 




public  String excutePost(String targetURL, String body)
      {
        URL url;
        HttpURLConnection connection = null;  
        try {
          //Create connection
          url = new URL(targetURL);
          connection = (HttpURLConnection)url.openConnection();
          connection.setRequestMethod("POST");
          connection.setRequestProperty("Content-Type", 
               "application/json");

          connection.setUseCaches (false);
          connection.setDoInput(true);
          connection.setDoOutput(true);

          //Send request
          DataOutputStream wr = new DataOutputStream (
                      connection.getOutputStream ());
          wr.writeBytes (body);
          wr.flush ();
          wr.close ();

          if(connection.getResponseCode() == HttpURLConnection.HTTP_OK){
          //Get Response    
              InputStream is = connection.getInputStream();
              BufferedReader rd = new BufferedReader(new InputStreamReader(is));
              String line;
              StringBuffer response = new StringBuffer(); 
              while((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
              }
              rd.close();
              return response.toString();
          }else{
              InputStream is = connection.getErrorStream();
              BufferedReader rd = new BufferedReader(new InputStreamReader(is));
              String line;
              StringBuffer response = new StringBuffer(); 
              while((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
              }
              rd.close();
          }

        } catch (Exception e) {

          e.printStackTrace();
          return null;

        } finally {

          if(connection != null) {
            connection.disconnect(); 
          }
        }
      }

我认为它会对你有所帮助。