我正在尝试使用Android手机中的REST访问服务器的Web服务(我在网络中)。在路由器中,我已完成“路由”以访问来自外部的所有查询,但路由器具有用户和密码。
我的问题是,是否需要在HTTP Post或HTTP Client中添加一些代码才能访问我的路由器,因为所有连接都会给我HttpHostConnectException: Connection to http://myipaddress:myport refused
我尝试了一些代码,但这不起作用。
@Override
protected Void doInBackground(Object... params) {
kkk = ((Integer) params[2]);
parametros = params;
Log.i("SendOnlyOneFact", "Guardando datos de la actividad " + kkk);
Thread.currentThread().setName("NA_SendOnlyOneFact-" + kkk);
// Guardar los datos creados
getActividades().get(kkk).saveData((android.app.Activity) params[1]);
// Serializar los datos creados
String cosa_serializada = getActividades().get(kkk).getMeasure()
.serializeData(getActividades().get(kkk), (android.app.Activity) params[1]);
// Obtener el XML a partir de ese arraylist
// Enviarlo mediante REST
HttpHost targetHost = new HttpHost(((GateDefinition) params[0]).getServer(),
((GateDefinition) params[0]).getPort(), "http");
HttpPost httpPost = new HttpPost("http://" + ((GateDefinition) params[0]).getServer() + ":"
+ ((GateDefinition) params[0]).getPort() + "/" + ((GateDefinition) params[0])
.getWeb_service());
// Also be sure to tell the server what kind of content we are sending
httpPost.setHeader("content-type", "text/plain");
// Something like this, but this doesn't work :(
ArrayList<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("login", "1234"));
nvps.add(new BasicNameValuePair("password", "1234"));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF_8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
StringEntity entity = new StringEntity(cosa_serializada, "UTF-8");
entity.setContentType("text/plain");
httpPost.setEntity(entity);
// execute is a blocking call, it's best to call this code in a
// thread separate from the ui's
response = httpClient.execute(targetHost, httpPost);
} catch (SocketException ex) {
Log.e("SendOnlyOneFact", "No existe conexión con el servidor");
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
编辑:我使用数据连接进行测试并且它可以工作,但是使用wifi它会给我这个例外,我不知道为什么! :○