【问题标题】:How to send data to server in android? (Beginner)如何在android中向服务器发送数据? (初学者)
【发布时间】:2016-02-12 13:20:48
【问题描述】:

我一直在尝试将 JSON 数据发送到服务器。但是,由于 NameValuePair 已被弃用,我的努力失败了。并且 okHttp 给出了一些错误,例如在库类路径中找不到 okie.string。有人知道吗?请给我一些其他的技巧。然而,我尝试了很多谷歌,这些文章没有帮助,因为文章太旧了。

任何链接或示例肯定会有所帮助。

【问题讨论】:

  • 这个问答对你有很大帮助。 stackoverflow.com/questions/23220695/…
  • 使用更高级别的库,例如 Retrofit 或 Volley
  • 尝试使用 Volley 或 Picasso。他们为你做了很多工作。它们的性能也更好。我从不尝试毕加索。排球链接:developer.android.com/training/volley/simple.html
  • 我做了一个发送json数据的项目,正在找,给我5分钟。
  • 您可以尝试使用邮递员 Chrome 发送 json 吗?我在响应上写我的代码 :D 但要知道是否所有都在服务器上工作。

标签: android json data-transfer


【解决方案1】:

为此使用改造。 Retrofit Update

【讨论】:

    【解决方案2】:

    好的,这就是我所做的,我将编写自己的 HttpRequest 库,而不是默认库。如果要使用此代码,您必须进行很多更改,但是我认为指导性很好,以后我会更好地编写代码。

    首先你必须以这种方式在 android 上对你的数据进行 jsonify:

    private JSONObject jsonifyData() throws JSONException {
            JSONArray jsonArray = new JSONArray();
    
            // first we begin with array form
            jsonArray.put(location.getLongitude());
            jsonArray.put(location.getLatitude());
    
            JSONObject mainObject = new JSONObject();
            mainObject.put(LOC,jsonArray);
    
            // here we put the rest of the data
            for ( String loc_key : location.getKeys())
                mainObject.put(loc_key, location.getParam(loc_key));
    
            for ( String key : ApplicationData.commercial_keys) {
                if ( !key.equalsIgnoreCase(ApplicationData.SERIAL) && comercial.containsKey(key))
                    mainObject.put(key, comercial.get(key));
            }
    
            mainObject.put(API_DEVICE, t_device);
            mainObject.put(API_SCOPE, t_scope);
            mainObject.put(API_OS, API_ANDROID);
    
            String ip = "0.0.0.0";
    
            mainObject.put(API_IP, ip); // IP de salida del sitio
    
            return mainObject;
        }
    

    我为那项工作创建了这个方法。我认为这份工作没有困难,适当的时候把我自己的转换,但有点修改把你的。

    然后,当你有一个 json 格式时,必须放 headers 并发送数据:

    try {
                    JSONObject data = jsonifyData();
                    Log.d(TAG, data.toString());
    
                    String[] HEAD = {"Content-Type"};
    
                    HashMap<String, String> cabeceras = new HashMap<>();
                    cabeceras.put("Content-Type", "application/json");
    
                    // you can ignore much of this
                    HttpRequest register = new HttpRequest(
                            'your_url',
                            null
                    );
                    register.setMethod("POST", 1);
                    register.setHeaders(HEAD, cabeceras);
                    register.setQuery(data.toString());
    
                    register.start();
                    register.join();
    
                    upload_data = true;
    
                } catch (JSONException | MalformedURLException | InterruptedException e) {
                    e.printStackTrace();
                }
    }
    

    如果你看到了,我使用的是 HttpRequest,它不是默认的!!我创建了一个同名的,这是 POST 的代码:

    private JSONObject POST() throws JSONException {
        JSONObject response = null;
        BufferedReader bufferedReader = null;
        InputStreamReader in = null;
        HttpURLConnection conn = null;
    
        try {
    
            conn = (HttpURLConnection) this.url.openConnection();
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);
            conn.setDoOutput(true);
            conn.setRequestMethod(POST);
    
            for (String KEY : KEYS) conn.setRequestProperty(KEY, headers.get(KEY));
    
            conn.connect();
    
            PrintWriter out = new PrintWriter(conn.getOutputStream());
            out.print(postParameters);
            Log.d("HttpRequest--->","DATA TO SEND: "+postParameters);
            out.close();
    
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                in = new InputStreamReader(conn.getInputStream());
                bufferedReader = new BufferedReader(in);
                String line;
                StringBuilder buffer = new StringBuilder();
                while ((line = bufferedReader.readLine()) != null) {
                    buffer.append(line);
                    buffer.append('\r');
                }
    
                bufferedReader.close();
    
                in.close();
                response = new JSONObject(buffer.toString());
            }
    
            conn.disconnect();
    
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (conn != null) {
                    conn.disconnect();
                }
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        return response;
    }
    

    【讨论】:

    • 我想我会选择 Retrofit。这么多代码有点难以维护。
    猜你喜欢
    • 2019-11-08
    • 1970-01-01
    • 1970-01-01
    • 2022-07-19
    • 2017-07-21
    • 2011-12-21
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多