0

我需要从移动 android 应用程序向服务器端应用程序发送 http POST 请求。此请求需要在正文中包含 json 消息和一些键值参数。我正在尝试编写此方法:

 public static String makePostRequest(String url, String body,  BasicHttpParams params) throws ClientProtocolException, IOException {
        Logger.i(HttpClientAndroid.class, "Make post request");
        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(body);
        httpPost.setParams(params);
        httpPost.setEntity(entity);
        HttpResponse response = getHttpClient().execute(httpPost);
        return handleResponse(response);
    }

在这里,我设置参数以通过方法 setParams 请求并通过 setEntity 设置 json 正文。但这行不通。任何人都可以帮助我吗?

4

1 回答 1

1

你可以使用 aNameValuePair来做到这一点............

下面是我项目中的代码,我使用 NameValuePair 发送 xml 数据并接收 xml 响应,这将为您提供一些关于如何将其与 JSON 一起使用的想法。

public String postData(String url, String xmlQuery) {



    final String urlStr = url;
    final String xmlStr = xmlQuery;
    final StringBuilder sb  = new StringBuilder();


    Thread t1 = new Thread(new Runnable() {

        public void run() {

            HttpClient httpclient = new DefaultHttpClient();

            HttpPost httppost = new HttpPost(urlStr);


            try {

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                        1);
                nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));

                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                HttpResponse response = httpclient.execute(httppost);

                Log.d("Vivek", response.toString());

                HttpEntity entity = response.getEntity();
                InputStream i = entity.getContent();

                Log.d("Vivek", i.toString());
                InputStreamReader isr = new InputStreamReader(i);

                BufferedReader br = new BufferedReader(isr);

                String s = null;


                while ((s = br.readLine()) != null) {

                    Log.d("YumZing", s);
                    sb.append(s);
                }


                Log.d("Check Now",sb+"");




            } catch (ClientProtocolException e) {

                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } 
        }

    });

    t1.start();
    try {
        t1.join();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    System.out.println("Getting from Post Data Method "+sb.toString());

    return sb.toString();
}
于 2012-10-12T17:59:42.870 回答