如何在android中使用post方法发送json数据?

时间:2015-06-02 10:18:13

标签: android json web-services

I have Url and parameter "data":
URL: http://www.xxxx.ru/mobile-api-v1/query/
data={«type":1,"body":{"sortType":0,"categoryId":0,"count":50,"authorId":0,"lastId":0}}

如何添加关键字“data =”?现在错误“错误的请求”

1 个答案:

答案 0 :(得分:0)

这样做:

InputStream is = null;
        String result = "";
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("data","your data"));
            Log.e("",String.valueOf(nameValuePairs));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
        }
        try{
            if(is != null){
                result = convertInputStreamToString(is);
                Log.e("result", result);
            }else{
                result = "Did not work!";
            }
        }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
        }

//这是从服务器

打印您对String的响应
 public void String convertInputStreamToString(InputStream inputStream) {
            BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
            String line = "";
            String result = "";
            try {
                while((line = bufferedReader.readLine()) != null)
                    result += line;
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }

请将此设置为方法,这是调用post方法。