duandan4680 2015-02-01 18:10
浏览 29
已采纳

从android上的php文件发布并获得json的结果

I am Newbie in android. and i have searched alot and found many many codes but still i have problem.

i have a simple php like : (it has two variables like q & number)

http://domain.tld/post.php

and after posting data to this page, there will be a result in JSON format.

I want to get that output on the php page, and Toast that value on the android (i mean i want to have that value on a variable in eclipse)

I have checked this code :

public void postData() {
     // Create a new HttpClient and Post Header
     HttpClient httpclient = new DefaultHttpClient();
      HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("id", "12345"));
    nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}
} 

But i can't get the output with this.

  • 写回答

1条回答 默认 最新

  • douyuefu1372 2015-02-01 18:34
    关注

    You must use a Json parser. Please find the ServiceHandler which handles get/post requests to your server.

    ServiceHandler.java

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.util.List;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.HttpVersion;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.utils.URLEncodedUtils;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.params.BasicHttpParams;
    import org.apache.http.params.CoreProtocolPNames;
    import org.apache.http.params.HttpParams;
    
    import android.util.Log;
    
    public class ServiceHandler {
    
        static InputStream is = null;
        static String response = null;
        public final static int GET = 1;
        public final static int POST = 2;
    
        public ServiceHandler() {
    
        }
    
        /*
         * Making service call
         * @url - url to make request
         * @method - http request method
         * */
        public String makeServiceCall(String url, int method) {
            return this.makeServiceCall(url, method, null);
        }
    
        /*
         * Making service call
         * @url - url to make request
         * @method - http request method
         * @params - http request params
         * */
        public String makeServiceCall(String url, int method,
                List<NameValuePair> params) {
            try {
                // http client
    
                HttpParams paramsH = new BasicHttpParams();
                paramsH.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
                HttpClient httpClient = new DefaultHttpClient(paramsH);
    
                //DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpEntity httpEntity = null;
                HttpResponse httpResponse = null;
    
                // Checking http request method type
                if (method == POST) {
                    HttpPost httpPost = new HttpPost(url);
                    // adding post params
                    if (params != null) {
                        httpPost.setEntity(new UrlEncodedFormEntity(params));
                    }
    
                    httpResponse = httpClient.execute(httpPost);
    
                } else if (method == GET) {
                    // appending params to url
                    if (params != null) {
                        String paramString = URLEncodedUtils
                                .format(params, "utf-8");
                        url += "?" + paramString;
                    }
                    HttpGet httpGet = new HttpGet(url);
    
                    httpResponse = httpClient.execute(httpGet);
    
                }
                httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
    
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "
    ");
                }
                is.close();
                response = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error: " + e.toString());
            }
    
            return response;
    
        }
    }
    

    In youractivity.java, Call it like this

    String resulting_json = null;
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("id", "12345"));
    nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
    ServiceHandler jsonParser = new ServiceHandler();
    String URL = "http://domain.tld/post.php";
    resulting_json = jsonParser.makeServiceCall(URL, ServiceHandler.POST, params);
    Toast.makeText(youractivity.this, resulting_json, Toast.LENGTH_LONG).show();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看