send POST requests with Body in Android

断了今生、忘了曾经 提交于 2019-12-12 03:59:58

问题


I want to send a simple POST request in Android with a body equaling this : [{ "value": ["test"]}]

Since the request is very very simple, I tried to do it using this code :

 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();
          }

Can you help me to fix this problem ? I don't know how can I exactly send a body in this form ?

Thank you!


回答1:


Create a separate class to parse JSON like this:

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;

}

}

And call this method from 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);
    }

// Method to create JSON Object

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;
}


来源:https://stackoverflow.com/questions/32700391/send-post-requests-with-body-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!