在android中的服务器上发布数据

时间:2013-09-15 05:48:17

标签: android post

我正在尝试使用以下代码在服务器上发布数据,但是数据仅针对一个字段发布,其他字段则发布为空。我的代码中有什么问题。我需要在我的Android应用程序中做任何其他更改吗?

public void postData(String name,String email,String mobile,String subject,String          message,String url)
{
    // Create a new HttpClient and Post Header

    Log.i("name",name);
    Log.i("email",email);
    Log.i("subject",subject);
    Log.i("mobile",mobile);
    Log.i("url",url);

    try {
        // Add your data
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);

        nameValuePairs.add(new BasicNameValuePair("name", subject));
        nameValuePairs.add(new BasicNameValuePair("email",subject));
        nameValuePairs.add(new BasicNameValuePair("mobile", subject));
        nameValuePairs.add(new BasicNameValuePair("subject", subject));
        nameValuePairs.add(new BasicNameValuePair("message", subject));

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));


        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity=response.getEntity();

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }

我的代码中有什么问题?

2 个答案:

答案 0 :(得分:0)

我不能说传递nameValuePairList是绝对错误的,但我传递给httpPost.setEntity()的对象是MultipartEntity。

MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("KEY", new StringBody("some string"));
reqEntity.addPart("ANOTHER_KEY", new StringBody("another string"));
httpPost.setEntity(reqEntity)

MultipartEntity是Apache Http Components的一部分

http://hc.apache.org/downloads.cgi

http客户端下载包含该类的httpmime-4.x.x.jar。你只需要httpmime jar,其余你不需要。

答案 1 :(得分:0)

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);

    nameValuePairs.add(new BasicNameValuePair("name", subject));
    nameValuePairs.add(new BasicNameValuePair("email",subject));
    nameValuePairs.add(new BasicNameValuePair("mobile", subject));
    nameValuePairs.add(new BasicNameValuePair("subject", subject));
    nameValuePairs.add(new BasicNameValuePair("message", subject));

    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

您的代码对我来说很好看。检查subject是否为空。
因为您已使用subject设置了所有内容!