如何在HttpClient中进行请求?

发布于 2024-11-06 08:01:29 字数 344 浏览 1 评论 0原文

我已经使用 jersey 框架和 java 编写了 REST wed 服务。 如果用户想在curl中请求HttpGet,他需要这样写:

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

现在,我正在实现将调用Web服务的android。 有谁知道如何在android中使用HttpClient调用Web服务? 如何在HttpClient中设置用户名和密码以与curl命令-u username:password匹配?

谢谢

I have write REST wed service using jersey framework and java.
If user want to request HttpGet in curl he need to write like:

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

Now, I am implement android which will call web service.
Do anyone know how to use HttpClient in android to call web service?
How to set username and password in HttpClient in order to match with curl command -u username:password?

thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

爱情眠于流年 2024-11-13 08:01:29
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();

    }


}
}

希望这段代码会有所帮助

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();

    }


}
}

Hope this code will help

一腔孤↑勇 2024-11-13 08:01:29

@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);
    }
}

@sudo try this simple code

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);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文