开发者

http post request for android

I want to send POST request in java开发者_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,


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.


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.


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....

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜