【问题标题】:How to send json data using post method in android?如何在android中使用post方法发送json数据?
【发布时间】:2015-06-02 10:18:13
【问题描述】:
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=”?现在错误“错误请求”

【问题讨论】:

  • data 是您的JSONObject。因此,您需要将所有值放入 JSONObject 并以原始数据格式发布该 json 对象。

标签: android json web-services


【解决方案1】:

这样做:

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

//这是从服务器将您的响应打印到字符串中

 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 方法的方式。

【讨论】:

    猜你喜欢
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多