有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

安卓的java http post请求

我想用java为安卓发送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) 个答案

  1. # 1 楼答案

    Javadoc声明:

    A name / value pair parameter used as an element of HTTP messages.

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

    由于HTTP POST不会将属性附加到URL(比如说),所以它是以实体体的形式进行的。可以有一个简单的基于字符串的实体或基于MIME的实体体

    NameValuePair实现了名为^{}的classed,您可以提供一个参数和一个值(将其视为HTTP参数)

  2. # 3 楼答案

    你要发什么计划?http还是https?您是否使用ClientConnectionManagerHttpParams正确设置了客户端?你的日志中有哪些例外

    我看到的一些用于发布数据的代码(假设您的客户端设置正确)之间的唯一区别是,我在execute方法中使用了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,则需要为客户端设置更多信息,以便它能够处理密钥库要求和连接的其他安全方面