【问题标题】:Android | Send “POST” JSON Data to Server安卓 |向服务器发送“POST” JSON 数据
【发布时间】:2016-04-05 22:43:54
【问题描述】:

我使用此代码使用 android 将发布数据发送到服务器。谁能给我任何想法或您的示例如何将 POST 或 GET json 数据发送到服务器 TOMCAT ..! 步骤提示:

  1. 创建 HttpClient
  2. 向给定的 URL 发出 POST 请求
  3. 构建 jsonObject
  4. 将 JSONObject 转换为 JSON 到字符串
  5. 将 json 设置为 StringEntity
  6. 设置 httpPost 实体
  7. 设置一些标头来通知服务器内容的类型
  8. 对给定的 URL 执行 POST 请求
  9. 作为输入流接收响应
  10. 将输入流转换为字符串
  11. 返回结果

    private class HttpAsyncTask extends AsyncTask<String, Void, String> {
    
            @Override
            protected String doInBackground(String... urls) {
    
            person = new Person();
            person.setName(etName.getText().toString());
            person.setCountry(etCountry.getText().toString());
            person.setTwitter(etTwitter.getText().toString());
    
            return POST(urls[0],person);
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
       }
    }
    

【问题讨论】:

    标签: java android


    【解决方案1】:

    您正在使用 HttpClient。实际上,Android 弃用了 HttpClient 的 HttpClient,您需要“HttpURLConnection”进行 POST 请求检查这里的示例之一:here

    更新:

    您需要为示例代码添加以下两行以满足您的要求。

    conn.addRequestProperty("Accept", "application/json");
    conn.addRequestProperty("Content-Type", "application/json");
    

    在给定的示例代码中:

    conn.setDoOutput(true);
    //Add the following line to the given sample
    ===============> updated for JSON POST <========================= 
    conn.addRequestProperty("Accept", "application/json");
    conn.addRequestProperty("Content-Type", "application/json");
    ===============> updated for JSON POST <========================= 
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("firstParam", paramValue1));
    params.add(new BasicNameValuePair("secondParam", paramValue2));
    params.add(new BasicNameValuePair("thirdParam", paramValue3));
    

    【讨论】:

    • 当然是我的朋友,但我使用 json 从服务器发布或获取数据。还有其他示例吗?
    【解决方案2】:

    如果你需要获取数据试试这个...

    try{
        URL url = new URL("http://www.youraddresheredude.com/andthefile");
        //Open the connection here, and remember to close it when job its done.
        URLConnection conn = url.openConnection();
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setDoOutput(true);
    
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        //theJSONYouWantToSend should be the JSONObject as String
        wr.write(convertStandardJSONString(theJSONYouWantToSend));  //<--- sending data.
    
        wr.flush();
    
        //  Here you read any answer from server.
        BufferedReader serverAnswer = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = serverAnswer.readLine()) != null) {
    
            System.out.println("LINE: " + line); //<--If any response from server
            //use it as you need, if server send something back you will get it here.
        }
    
        wr.close();
        serverAnswer.close();
    
    } catch (Exception e) {
        Log.e("Cuack", "Something its wrong");
    }
    

    【讨论】:

    • 你真的应该添加一些解释为什么这个代码应该工作 - 你也可以在代码本身中添加 cmets - 在它的当前形式中,它没有提供任何可以帮助其余部分的解释社区了解您为解决/回答问题所做的工作。
    • 问题问如何将数据发送到服务器而不是从服务器取回数据。
    • 您想知道数据是否在服务器上。
    【解决方案3】:
    public class JSONParser {
    
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    static String responseString;
    
    // constructor
    public JSONParser() {
    
    }
    
    // function get json from url
    // by making HTTP POST or GET mehtod
    public static JSONObject makeHttpRequest(String url, String method,
                                             List<NameValuePair> params) {
    
        // Making HTTP request
        Log.d("json class", url + "," + method + "," + params.toString());
        try {
    
            // check for request method
            if (method == "POST") {
                // request method is POST
                // defaultHttpClient
                Log.d("json class", "post method");
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                Log.d("json class", "HttpPost" + httpPost);
                httpPost.setEntity(new UrlEncodedFormEntity(params));
                Log.d("json class", "setentity");
                HttpResponse httpResponse = httpClient.execute(httpPost);
    
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                int responce_code = httpResponse.getStatusLine()
                        .getStatusCode();
                Log.d("responce code", "response method");
                Log.d("responce code", "" + responce_code);
                StatusLine statusLine = httpResponse.getStatusLine();
    
                if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                    Log.i("RESPONSE", "6");
                    /*
                     * httpResponse.getEntity().writeTo(out); out.close();
                     * String responseString = out.toString(); Log.i("RESPONSE",
                     * ""+responseString);
                     */
                    // ..more logic
                } else {
                    Log.d("RESPONSE", "null pointer exception");
                    // Closes the connection.
                    httpResponse.getEntity().getContent().close();
                    throw new IOException(statusLine.getReasonPhrase());
                }
    
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
    
            } else if (method == "GET") {
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                Log.i("url", url);
                HttpGet httpGet = new HttpGet(url);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                HttpResponse httpResponse = httpClient.execute(httpGet);
                int responce_code = httpResponse.getStatusLine()
                        .getStatusCode();
                Log.d("responce code", "response method");
                Log.d("responce code", "" + responce_code);
    
                StatusLine statusLine = httpResponse.getStatusLine();
    
                if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
    
                    Log.d("RESPONSE", "6");
                    httpResponse.getEntity().writeTo(out);
                    Log.d("RESPONSE", "7");
                    out.close();
                    Log.d("RESPONSE", "8");
                    responseString = out.toString();
                    Log.d("RESPONSE", "9");
                    Log.i("RESPONSE", "" + responseString);
                    // ..more logic
                } else {
                    Log.d("RESPONSE", "null pointer exception");
                    // Closes the connection.
                    httpResponse.getEntity().getContent().close();
                    throw new IOException(statusLine.getReasonPhrase());
                }
                /*
                 * 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 = responseString.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);
        } catch (JSONException e) {
    
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        // return JSON String
        return jObj;
    }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-11
      • 2013-11-17
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 2020-04-13
      • 2018-11-18
      • 1970-01-01
      相关资源
      最近更新 更多