连接PHP的问题:withg java.lang.Exception:HTTP错误:401

时间:2012-03-15 11:20:01

标签: java php httpclient httpresponse http-get

我有这个代码,谁应该连接到php远程文件,并且应该获得表示XML文件的String。但有些事情是错的,它给了我错误401.

变量url是php的方向:

String response=getXML("http://ficticiousweb.com/scripts/getMagazinesList.php");

如果我在webbrowser上粘贴真正的方向(这是一个虚构的方向),它可以工作并给我XML。

这是我的代码:

public String getXML(String url){
    try{
        StringBuilder builder = new StringBuilder();
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpclient.execute(httpget);
        int statuscode = response.getStatusLine().getStatusCode();
        if(statuscode == 200)
        {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null)  builder.append(line);               
        }
        else throw new Exception("HTTP error: " + String.valueOf(statuscode));
        return builder.toString();
    }catch(Exception e){e.printStackTrace();}
    return null;
}

代码有什么问题?

感谢

2 个答案:

答案 0 :(得分:1)

您需要登录所请求的网站才能下载或访问xml。这可以通过基于支持的身份验证的模式来完成。通常,使用两种类型的模式。 基本摘要。下面的代码将帮助您获得BASIC AUTH。

HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;
    String _username = "username";
    String _password = "password";
    try {
         ((AbstractHttpClient) httpclient).getCredentialsProvider().setCredentials(
                new org.apache.http.auth.AuthScope(webhostname, webport)),
                new org.apache.http.auth.UsernamePasswordCredentials(_username, _password));

        response = httpclient.execute(new HttpGet(completeurlhere));
        StatusLine statusLine = response.getStatusLine();
        if(statusLine.getStatusCode() == HttpStatus.SC_OK) {
            try {
                InputStream is = response.getEntity().getContent();
                this._data = is;

            } catch(Exception ex) {
                Log.e("DBF Error",ex.toString());
            }                
        } else {
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch(ClientProtocolException cpe) {
        Log.e("ClientProtocolException @ at FPT",cpe.toString());
    } catch(Exception ex) {
        Log.e("Exception at FETCHPROJECTASK",ex.toString());
    }

答案 1 :(得分:0)

好的401意味着您没有被授权执行GET请求。您应该询问网站如何验证请求...

通过HTTP请求中的授权标头进行授权。你应该研究一下,并且可能用你的凭证填写那个标题......(如果服务器接受了)