通过POST方法在java中发送JSON数组

时间:2014-08-01 07:33:12

标签: java web-services post

我有一个json数组准备发送到php服务器。当我尝试通过GET方法发送它时,它告诉URL太长。所以我决定通过POST发送它。我想知道有没有办法成功地做到这一点?

2 个答案:

答案 0 :(得分:0)

由于您没有提供有关您使用的任何库的详细信息,因此这是以某种方式进行的。但你可以在第3点看看http://www.mkyong.com/webservices/jax-rs/restful-java-client-with-jersey-client/,看看如何实现这一目标。

答案 1 :(得分:-1)

我用这段代码发送我的json字符串

 private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {



            return POST(urls[0]);
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
       }
    }
    public static String POST(String url){
    InputStream inputStream = null;
    String result = "";
    try {

        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // 2. make POST request to the given URL
        HttpPost httpPost = new HttpPost(url);

        String json = "what ever your string is";





     // 5. set json to StringEntity
        StringEntity se = new StringEntity(json);

        // 6. set httpPost Entity
        httpPost.setEntity(se);

        // 7. Set some headers to inform server about the type of the content   
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httpPost);

        // 9. receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();

        // 10. convert inputstream to string
        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }
   // 11. return result
    return result;

  }

    private static String convertInputStreamToString(InputStream inputStream) throws IOException   
    {
    // TODO Auto-generated method stub

        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
      String line = "";
      String result = "";
       while((line = bufferedReader.readLine()) != null)
        result += line;

        inputStream.close();
        return result;

    }



}

使用它来执行请求

new HttpAsyncTask().execute("your URL");