【问题标题】:Getting data from a server with BasicValuePairName?使用 BasicValuePairName 从服务器获取数据?
【发布时间】:2014-05-18 18:13:18
【问题描述】:

我正在使用 JSONParser 类创建要发送到服务器的 JSON,但我现在需要使用它来接收信息,但我不知道该怎么做,我是菜鸟,抱歉。我使用下一部分代码和以下类创建 json。

// Building Parameters
            params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("userid", thought.getUser()));
            params.add(new BasicNameValuePair("timestamp", "" + thought.getTimestamp()));
            params.add(new BasicNameValuePair("message", thought.getMessage()));
            params.add(new BasicNameValuePair("address", thought.getAddress()));
            params.add(new BasicNameValuePair("latitude", "" + thought.getLatitude()));
            params.add(new BasicNameValuePair("longitude", "" + thought.getLongitude()));

            // getting JSON Object
            // Note that create product url accepts POST method
            JSONParser jsonParser = new JSONParser();
            JSONObject json = jsonParser.makeHttpRequest(url_create_thought, "POST", params);

JSONParser.class

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method.equalsIgnoreCase("POST")){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method.equalsIgnoreCase("GET")){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity 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, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

服务器中的部分我觉得还可以。

服务器获取值部分

<?php

/*
 * Following code will list all the products
 */

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// get all products from products table
$result = mysql_query("SELECT * FROM thoughts") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
    // looping through all results
    // products node
    $response["thoughts"] = array();

    echo '<center><div class="datagrid"><table>';
    echo '<thead><tr><th>ID</th><th>USERID</th><th>TIMESTAMP</th><th>MESSAGE</th><th>ADDRESS</th><th>LATITUDE</th><th>LONGITUDE</th></tr></thead><tbody>';

    while ($row = mysql_fetch_array($result)) {
        // temp user array
        $thought = array();
        $thought["id"] = $row["id"];
        $thought["userid"] = $row["userid"];
        $thought["timestamp"] = $row["timestamp"];
        $thought["message"] = $row["message"];
        $thought["address"] = $row["address"];
        $thought["latitude"] = $row['latitude'];
        $thought["longitude"] = $row['longitude'];

        echo '<tr><td>'.$row['id'].'</td><td>'.$row['userid'].'</td><td>'.$row['timestamp'].'</td><td>'.$row['message'].'</td><td>'.$row['address'].'</td><td>'.$row['latitude'].'</td><td>'.$row['longitude'].'</td></tr>';

        // push single product into final response array
        array_push($response["thoughts"], $thought);
    }
    // success
    $response["success"] = 1;

    // echoing JSON response
    //echo json_encode($response);
    echo '</table></center>';
} else {
    // no products found
    $response["success"] = 0;
    $response["message"] = "No events found";

    // echo no users JSON
    echo json_encode($response);
}

?>

在android中获取数据的正确方法是什么?我需要在参数中添加什么?

JSONParser jsonParser = new JSONParser();
JSONObject json = jsonParser.makeHttpRequest(url_create_thought, **"GET"**, params);

感谢您的帮助。

【问题讨论】:

  • 我可以请您发布您的服务器响应。因为我认为您的服务器代码不正确。我这么说的原因是当接收到 json 响应时,您应该“仅”回显 json 响应,仅此而已。你的代码应该只使用echo json_encode($response) 没有其他应该回显。您正在使用echo 用于表格和其他一些会在 json 格式中产生错误的东西。

标签: php android json get


【解决方案1】:

这是一个从 json-return url 获取你想要的东西的简单方法:

String sURL = "http://freegeoip.net/json/"; //just a string

// Connect to the URL using java's native library
URL url = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();

// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //may be an array, may be an object. 
zipcode=rootobj.get("zipcode").getAsString();//just grab the zipcode

【讨论】:

  • 你导入“com.google.gson.JsonElement”jar 文件了吗?从这里下载:code.google.com/p/google-gson/downloads/list
  • 没有。我现在要导入它。我会评论结果。
  • JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); “请求”无法解决。其他图书馆?谢谢
  • 您使用此命令创建请求实例:“HttpURLConnection 请求”。它是否正确创建?如果不检查 HttpURLConnection 是否已正确导入。这也是android api的核心。无需为此导入第三方 jar
  • MalFormedJSON 异常... :s
猜你喜欢
  • 2014-08-04
  • 1970-01-01
  • 1970-01-01
  • 2017-09-20
  • 1970-01-01
  • 2012-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多