как сделать запрос в HttpClient? - PullRequest
0 голосов
/ 12 мая 2011

У меня есть сервис REST wed, использующий фреймворк и java. Если пользователь хочет запросить HttpGet в curl, он должен написать так:

curl -u username:password -H "Content-Type:application/...." http://localhost:8080/project/user

Теперь я использую Android, который будет вызывать веб-сервис. Кто-нибудь знает, как использовать HttpClient в Android для вызова веб-службы? Как установить имя пользователя и пароль в HttpClient, чтобы соответствовать команде curl -u username:password?

спасибо

Ответы [ 2 ]

2 голосов
/ 12 мая 2011
package com.android.demo;


import org.apache.http.HttpEntity;

import org.apache.http.HttpHost;

import org.apache.http.HttpResponse;

import org.apache.http.auth.AuthScope;

import org.apache.http.auth.UsernamePasswordCredentials;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.auth.BasicScheme;

import org.apache.http.impl.client.AbstractHttpClient;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.protocol.BasicHttpContext;

import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.Bundle;

public class MyActivity extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
     /* START Test/Play with beanstalk API */
    String username = "user1";
    String host = "my.host.com";
    String password = "password";

    String urlBasePath = "http://" + username + ".host.com/api/";
    String urlApiCall_FindAllRepositories = urlBasePath
            + "repositories.xml";

    try {
        HttpClient client = new DefaultHttpClient();

        AuthScope as = new AuthScope(host, 443);
        UsernamePasswordCredentials upc = new UsernamePasswordCredentials(
                username, password);

        ((AbstractHttpClient) client).getCredentialsProvider()
                .setCredentials(as, upc);

        BasicHttpContext localContext = new BasicHttpContext();

        BasicScheme basicAuth = new BasicScheme();
        localContext.setAttribute("preemptive-auth", basicAuth);

        HttpHost targetHost = new HttpHost(host, 443, "https");

        HttpGet httpget = new HttpGet(urlApiCall_FindAllRepositories);
        httpget.setHeader("Content-Type", "application/xml");

        HttpResponse response = client.execute(targetHost, httpget,
                localContext);

        HttpEntity entity = response.getEntity();
        Object content = EntityUtils.toString(entity);



    } catch (Exception e) {
        e.printStackTrace();

    }


}
}

Надеюсь, этот код поможет

1 голос
/ 13 мая 2011

@ sudo попробуйте этот простой код

HttpURLConnection conn = null;

    try {
        // The formated URL will be "http://www.androidcoder.org:80".
        URL url = new URL(String.format("http://%s:%d/%s", mIpAddress, mPort, mSubPage));
        conn = (HttpURLConnection) url.openConnection();

        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-length", "0");
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.setConnectTimeout(TIMEOUT);
        conn.setReadTimeout(TIMEOUT);

        // NOTE: Below is used to perform the http authentication. It is working in JAVA but not
        // always working in Android platform.

        // Set to use the default HTTP authentication. Working in JAVA, but not working in
        // Android.
        Authenticator.setDefault(new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("user1", "pass1".toCharArray());
            }
        });
        conn.connect();

        System.out.println(conn.getResponseCode()); // <-- The request will stop here if running
                                                    // in Android.
        System.out.println(conn.getResponseMessage());

        printOutput(conn);

    } catch (MalformedURLException e) {
        // TODO: Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // Operation timed out.
        System.out.println(e.getMessage());
        e.printStackTrace();
    } finally {
        if (conn != null) {
            conn.disconnect();
            conn = null;
        }
    }
}

/**
 * @brief print the output of the HTTP connection.
 * @param conn [in] Http connection.
 */
private static void printOutput(HttpURLConnection conn) throws IOException {
    int length = 256;
    byte bytes[] = new byte[length];
    InputStream is = conn.getInputStream();

    while (is.available() > 0) {

        if (is.available() < length) {
            length = is.available();
        }
        conn.getInputStream().read(bytes, 0, length);
        System.out.println(bytes);
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...