连接PHP时出现问题:withg java.lang.异常:HTTP错误:401


Problems connecting with a PHP: withg java.lang.Exception: HTTP error: 401

我有这段代码,它应该连接到php远程文件,并且应该获得表示XML文件的String。但有点不对劲,它给了我错误401。

变量url是php:的方向

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

如果我在网络浏览器上粘贴真实的方向(这是一个虚构的方向),它就可以工作,并为我提供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;
}

代码出了什么问题?

感谢

您需要登录到请求的站点才能下载或访问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());
    }

401表示您无权执行GET请求。您应该询问网站如何验证请求。。。

通过HTTP请求中的Authorization Header进行授权。你应该对此进行调查,并可能用你的证书自己填写标题。。。(如果服务器接受)