http发布请求android

时间:2011-07-21 07:58:37

标签: java android

我想在java for android中发送POST请求。

我使用此代码:

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("myUrl");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("artist", "Amy Macdonald"));
        nameValuePairs.add(new BasicNameValuePair("title", "Don't Tell Me That It's Over"));
        nameValuePairs.add(new BasicNameValuePair("album", "Don't Tell Me That It's Over"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

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

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

问题是当我使用时:

HttpResponse response = httpclient.execute(httppost);

我得到一个例外,这个网络服务肯定是有效的,

3 个答案:

答案 0 :(得分:0)

Javadoc个州:

  

用作HTTP消息元素的名称/值对参数。

 parameter               = attribute "=" value
 attribute               = token
 value                   = token | quoted-string

由于HTTP POST不会将属性附加到URL(例如),它以实体主体的形式执行。您可以拥有一个简单的基于字符串的实体或基于MIME的实体主体。

NameValuePair已经实现了一个名为BasicNameValuePair的类别(想想它是LIKE HTTP参数),你提供了一个参数和一个值。

答案 1 :(得分:0)

你发布了什么方案? http或https?您是否使用ClientConnectionManagerHttpParams正确设置了客户端?你在日志中有什么例外?

我在发布数据的某些代码(假设您的客户端设置正确)之间看到的唯一区别是我在执行方法中使用httpContext,如下所示:

httpPost = new HttpPost(urlString);
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
response = httpClient.execute(httpPost, httpContext);
statusCode = response.getStatusLine().getStatusCode();

使用

在构造函数中设置上下文
httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, new BasicCookieStore());

如果您使用https,则需要为客户端设置更多信息,以便它可以处理密钥库要求和连接的其他安全方面。

答案 2 :(得分:0)

查看此帖子

http://www.softwarepassion.com/android-series-get-post-and-multipart-post-requests/

它有所有类型: httppost,httpget,带文件上传的httppost ....