我正在尝试将本地主机中的 µTorrent 的 web api 与 java 一起使用。这可行,但有时我会在此方法中遇到错误。
public String[] connectToWebAPI()
{
String guid = null;
String token = null;
String[] tokenAndGuid = new String[2];
targetHost = new HttpHost("127.0.0.1", 2222, "http");
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin"));
CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
try
{
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local
// auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
// Add AuthCache to the execution context
localcontext = new HttpClientContext();
localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
CookieStore cookieStore = new BasicCookieStore();
localcontext.setCookieStore(cookieStore);
HttpGet httpget = new HttpGet("http://127.0.0.1:2222/gui/");
HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
EntityUtils.consumeQuietly(response.getEntity());
httpget = new HttpGet("http://127.0.0.1:2222/gui/token.html");
response = httpclient.execute(targetHost, httpget, localcontext);
HttpEntity e = response.getEntity();
InputStream is = e.getContent();
StringWriter sw = new StringWriter();
IOUtils.copy(is, sw);
sw.flush();
sw.close();
is.close();
//<html><div id='token' style='display:none;'>gzB9zbMru3JJlBf2TbmwwklESgXW2hD_caJfFLvNBjmaRbLZ3kNGnSHrFlIAAAAA</div></html>
String t = sw.toString();
//Get token out of html
int start = "<html><div id='token' style='display:none;'>".length();
int end = t.indexOf("</div></html>");
token = t.substring(start,end);
EntityUtils.consumeQuietly(response.getEntity());
for(Cookie cookie : localcontext.getCookieStore().getCookies())
{
if(cookie.getName().equals("GUID"))
guid = cookie.getValue();
}
httpclient.close();
}
catch (Exception e)
{
tokenAndGuid[0] = "error";
return tokenAndGuid;
}
tokenAndGuid[0] = token;
tokenAndGuid[1] = guid;
return tokenAndGuid;
}
我得到的错误是在这个声明中:
httpclient.execute(targetHost, httpget, localcontext);
org.apache.http.conn.HttpHostConnectException: Connect to 127.0.0.1:2222 [/127.0.0.1] failed: Connection refused: connect
at org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:140)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:318)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:363)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:219)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:86)
谁能帮助我或给我一些见解?先感谢您。