如何使用REST将Json String发送到android中的参数中的java web服务?

时间:2014-04-08 11:59:56

标签: java android json web-services rest

Fiends,我将带有三个参数的JSON String发送到java web服务方法。但在java方法不能打印在控制台。请引导我从下面的代码中改变一下?

String json = "";
        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
        HttpConnectionParams.setSoTimeout(httpParams, 10000);
        HttpClient httpclient = new DefaultHttpClient();

        // Prepare a request object
        HttpPost httpPost = new HttpPost(url);
        HttpGet httpGet = new HttpGet(url);

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("name", "ghanshyam");
            jsonObject.put("country", "India");
            jsonObject.put("twitter", "ghahhd");

            json = jsonObject.toString();

            StringEntity se = new StringEntity(json);

            se.setContentEncoding("UTF-8");
            se.setContentType("application/json");

            // 6. set httpPost Entity
            System.out.println(json);

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

            //String s = doGet(url).toString();

            Toast.makeText(getApplicationContext(), "Data Sent", Toast.LENGTH_SHORT).show();

1 个答案:

答案 0 :(得分:0)

使用以下代码将json发布到Java Web服务:并将resopnse作为字符串获取。

    JSONObject json = new JSONObject();
    json.put("name", "ghanshyam");
    json.put("country", "India");
    json.put("twitter", "ghahhd");

    HttpPost post = new HttpPost(url);
    post.setHeader("Content-type", "application/json");
    post.setEntity(new StringEntity(json.toString(), "UTF-8"));
    DefaultHttpClient client = new DefaultHttpClient();
    HttpResponse httpresponse = client.execute(post);
    HttpEntity entity = httpresponse.getEntity();
    InputStream stream = entity.getContent();
    String result = convertStreamToString(stream);

并且您的convertStremToString()方法如下:

    public static String convertStreamToString(InputStream is)
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try
        {
            while ((line = reader.readLine()) != null)
            {
                    sb.append(line + "\n");
            } 
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                is.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return sb.toString();
}