繁体   English   中英

http 发布请求 android

[英]http post request for android

我想在 java 中为 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);

我得到了一个例外,这个网络服务肯定可以工作,

Javadoc 状态

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

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

由于 HTTP POST 没有 append 属性到 URL(据说),它以实体主体的形式进行。 您可以有一个简单的基于字符串的实体或基于 MIME 的实体主体。

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

您要发布到什么计划? 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,则需要使用更多信息设置客户端,以便它可以处理密钥库要求和连接的其他安全方面。

检查这个帖子

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

它有所有类型: httppost、httpget、httppost 和文件上传....

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM