【问题标题】:send POST requests with Body in Android在 Android 中使用 Body 发送 POST 请求
【发布时间】:2015-09-21 16:40:19
【问题描述】:

我想在 Android 中发送一个简单的 POST 请求,其正文等于:[{ "value": ["test"]}]

由于请求非常简单,我尝试使用以下代码:

 try {
      URL url = new URL("******"); 
      HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

      //headers   (all of them are simple strings)
      connection.setRequestMethod("POST");
      connection.setRequestProperty("X-OAPI-Key", "123****");
      connection.setRequestProperty("X-ISS-Key", "*******");
      connection.setRequestProperty("Content-Type", "application/json");

      //body that I want to send
      String urlParameters = "[{\"value\":[test]}]";

      // Send post request
      connection.setDoOutput(true);
      DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
      wr.writeBytes(urlParameters);
      wr.flush();
      wr.close();
     }

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

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

你能帮我解决这个问题吗?我不知道如何才能准确地以这种形式发送正文?

谢谢!

【问题讨论】:

  • 你想以JSONObject发送数据吗?
  • 尝试使用 Volley 库。
  • 在 Volley 中只需使用 POST 调用 StringRequest 就可以了!

标签: android request http-post


【解决方案1】:

创建一个单独的类来解析JSON,如下所示:

public class JSONParser {

/* Defining all variables */
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

/* Get Json object as respective response to url */
public JSONObject getJSONFromUrl(String url, JSONObject jObj) {

    Log.v("Requ. URL: ",url);
    // Making HTTP request
    try {
        // Default Http Client
        DefaultHttpClient httpClient = new DefaultHttpClient();
        // Http Post Header
        HttpPost httpPost = new HttpPost(url);
        StringEntity se = new StringEntity(jObj.toString());
        httpPost.setEntity(se);
        httpPost.setHeader("Content-type", "application/json");
        // Execute Http Post Request
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    /*
     * To convert the InputStream to String we use the
     * BufferedReader.readLine() method. We iterate until the BufferedReader
     * return null which means there's no more data to read. Each line will
     * appended to a StringBuilder and returned as String.
     */
    try {
        // Getting Server Response
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        // Reading Server Response
        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);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    Log.e("JSON Parser", jObj.toString());
    return jObj;

}

}

并从AsyncTask调用此方法

// Async Class for fetching live metal price from webapi
private class YourClassToFetchData extends AsyncTask<String, String, String>
{



    @Override
    protected String doInBackground(String... params) {

    jParser = new JSONParser();
        JSONObject jsonObject = jParser.getJSONFromUrl(
                URL, getConvertedinJson());

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
    }

//创建JSON对象的方法

private JSONObject getConvertedinJson() {

    JSONObject object = new JSONObject();
    try {
        object.put("", "");
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Log.v("JObj", "JObj " + object.toString());
    return object;
}

【讨论】:

  • 听起来对我来说太复杂了。你知道请一个更简单的方法吗?也许凌空图书馆没有?因为我不明白为什么在 Android 中发送一个简单的 post 请求如此复杂,而在 nodejs 中却太容易了。这是否意味着 Android 和 Java 不是强大的语言?
  • 如果您了解面向对象的编程概念,那么您就知道复杂性。如果知道如何使用AsyncTask 以及如何使用 GET 方法调用 API,则此代码非常简单。我正在尝试更多描述。
猜你喜欢
  • 2015-11-06
  • 1970-01-01
  • 2013-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-16
相关资源
最近更新 更多