gpt4 book ai didi

java - 使用 PHP : withg java. lang.Exception 连接时出现问题:HTTP 错误:401

转载 作者:行者123 更新时间:2023-12-01 15:29:36 25 4
gpt4 key购买 nike

我有这段代码,他应该连接到一个 php 远程文件并应该获取一个表示 XML 文件的字符串。但出了点问题,它给了我错误 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。这可以通过基于支持的经过身份验证的模式来完成。通常,使用两种类型的模式。 基本摘要。下面的代码将帮助您进行基本身份验证。

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

关于java - 使用 PHP : withg java. lang.Exception 连接时出现问题:HTTP 错误:401,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9718624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com