使用HttpPost在Android上发送字符串,而不使用nameValuePairs

时间:2013-04-18 10:04:21

标签: android string http-post

我正在寻找有关如何在Android上使用HttpPost方法发送信息的信息,我总是看到:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(posturl);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Name","Var1"));
params.add(new BasicNameValuePair("Name2","Var2"));

httppost.setEntity(new UrlEncodedFormEntity(params));    
HttpResponse resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();

问题是我无法做到这一点,因为我必须连接到接收XML格式的String的资源。

关于如何在不使用List<nameValuePair>

的情况下仅发送字符串的任何想法

3 个答案:

答案 0 :(得分:19)

您是否尝试过使用StringEntity?上面的代码可以更新为使用StringEntity,以下是生成的代码:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(posturl);


httppost.setEntity(new StringEntity("your string"));    
HttpResponse resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();

答案 1 :(得分:0)

您可以将JSON用作post参数。尝试参考FlexJson

答案 2 :(得分:-1)

// Sending HTTPs Requet to Server

    try {
        Log.v("GG", "Sending sever 1 - try");
        // start - line is for sever connection/communication
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(
                "10.0.0.1/abc.php");

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


        httppost.setEntity(new UrlEncodedFormEntity(
                nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        // end - line is for sever connection/communication
        InputStream is = entity.getContent();

        Toast.makeText(getApplicationContext(),
                "Send to server and inserted into mysql Successfully", Toast.LENGTH_LONG)
                .show();

        // Execute HTTP Post Request
        response= httpclient.execute(httppost);

        entity = response.getEntity();
        String getResult = EntityUtils.toString(entity);
        Log.e("response =", " " + getResult);



    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection "
                + e.toString());
    }