简体   繁体   中英

http post request for android

I want to send POST request in java for android.

I Use this code:

    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
    }

The problem is that when i use:

HttpResponse response = httpclient.execute(httppost);

i get an exception, and this webservice is working for sure,

The Javadoc States:

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

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

Since HTTP POST doesn't append attributes to an URL (per say), It does it in a form of Entity Body. You can have a simple string based entity or MIME based entity body.

NameValuePair has implemented classed called BasicNameValuePair which (think of it LIKE HTTP parameters) you provide a parameter and a value.

What scheme are you posting to? http or https? Have you set up the client correctly with a ClientConnectionManager and HttpParams ? What exceptions are you getting in your logs?

The only difference I see between some code I have for posting data (assuming your client is setup correctly) is that I use httpContext in the execute method like this:

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

where the context is setup in the constructor with

httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, new BasicCookieStore());

If you are using https, you'll need to setup the client with more information so it can handle the keystore requirements and other secure aspects of the connection.

Check this post

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

It got all type: httppost, httpget, httppost with file upload ....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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