Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/206.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Android中使用Body发送POST请求_Android_Request_Http Post - Fatal编程技术网

在Android中使用Body发送POST请求

在Android中使用Body发送POST请求,android,request,http-post,Android,Request,Http Post,我想在Android中发送一个简单的POST请求,其正文等于:[{“value”:[“test”]}] 由于请求非常简单,我尝试使用以下代码: try { URL url = new URL("******"); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); //headers (all of them are simple strings)

我想在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();
          }
你能帮我解决这个问题吗?我不知道我怎样才能把尸体以这种形式寄出去


谢谢大家!

创建一个单独的类来解析
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);
    }

您想以
JSONObject
的形式发送数据吗?尝试使用Volley库。在Volley中,只需使用POST调用StringRequest,就可以了!听起来对我来说太复杂了。你知道更简单的方法吗?也许截击图书馆没有?因为我不明白为什么发送一个简单的post请求在Android中如此复杂,而在nodejs中却如此简单。这是否意味着Android和Java不是功能强大的语言?如果你知道面向对象编程的概念,那么就知道了复杂性。如果知道如何使用
AsyncTask
以及如何使用GET方法调用API,那么这段代码非常简单。我正在尝试更多的描述。
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;
}