How can i make local http request in flutter? - laravel

when i make access on website on endpoint "http://localhost/newsapp_api/public/api/authors"it's work without any problem,but when i try this in flutter it shows me a problem.
message error:E/flutter (24506): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: SocketException: OS Error: Connection refused, errno = 111, address = localhost, port = 46873
codes:
authors_api.dart
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:news_app/utilities/api_utilities.dart';
import 'package:news_app/models/author.dart';
class AuthorsAPI {
Future<List<Author>> fetchAllAuthors() async {
// ignore: deprecated_member_use
List<Author> authors = List<Author>();
String allAuthorsApi = base_api + all_authors_api;
var url = Uri.parse(allAuthorsApi);
var response = await http.get(url);
print(response.statusCode);
print("*****************");
print(response.body);
}
}
api_utilities.dart
String base_api = "http://localhost/newsapp_api/public/api/authors";
String all_authors_api = "/api/authors";

make sure that you are not using any VPN or proxy server
try to use http://127.0.0.1 instead of http://localhost
hope this solve your problem

Note that localhost does not work with the Android emulator which uses 10.0.0.2
To support both Web and Android emulator use the (local) IP address of the server

You can make the server running on localhost avalible on your device like this:
adb reverse tcp:3000 tcp:3000
Please note that you should replace 3000 with the port that you srever is running on.
And that's it! Now you can access localhost from your device.

Related

UnknownHostException when trying to connect using websocket

I have a use case where I need to send 2 requests to the server. The output of first request is used in second request so the calls have to be synchronous. I am using ktor (OkHttp)client websocket for this. I am failing at first attempt to even connect to the server with this error
Exception in thread "main" java.net.UnknownHostException: https: nodename nor servname provided, or not known
I suspect I haven't split my url properly and thats why its not able to connect to host.
Couple of qns
Is there any benefit to using websocket instead of using 2 separate Http requests?
Is there a way I can just pass URL to the websocket request?
Best and easiest way to get response and send another request?
I have been able to find very limited documentation on ktor client websocket.
const val HOST = "https://sample.com"
const val PATH1 = "/path/to/config?val1=<val1>&val2=<val2>"
const val PATH2 = "/path/to/config?val=<response_from_first_req>"
fun useSocket() {
val client = HttpClient() {
install(WebSockets)
}
runBlocking {
client.webSocket(method = HttpMethod.Get, host = HOST, path = PATH1) {
val othersMessage = incoming.receive() as? Frame.Text
println(othersMessage?.readText())
println("Testing")
}
}
client.close()
}
Thanks in advance.

How to connect to RSK public nodes over websockets?

I am trying to connect to RSK Mainnet or RSK Testnet over websockets.
Here's what I tried for Mainnet:
const wsProvider = new Web3.providers.WebsocketProvider('ws://public-node.rsk.co');
const web3 = new Web3(wsProvider);
web3.eth.subscribe('newBlockHeaders', function(error, blockHeader){
if (!error) {
console.log("new blockheader " + blockHeader.number)
} else {
console.error(error);
}
});
with this result:
connection not open on send()
Error: connection not open
And I did the same with Testnet but using ws://public-node.testnet.rsk.co, getting similar outcome.
Neither of these work, as seen in the errors above.
How can I connect?
Milton
I am not sure, but I think websocket is not enabled in public nodes.
Usually it is not enabled in others public blockchain nodes that I know.
RSK public nodes expose JSON-RPC endpoints only over HTTP.
They do not expose JSON-RPC endpoints over websockets,
so unfortunately, you are not able to do exactly what you have described.
However, you can achieve something equivalent
by running your own RSK node,
and use this to establish websockets connections.
Here are the RSK
configuration options for RPC .
Also, you can see the default configuration values
in the "base" configuration file, for
rpc.providers.ws
ws {
enabled = false
bind_address = localhost
port = 4445
}
Additionally, you should include the /websocket suffix in your endpoint. Default websocket endpoint when running your own node is: ws://localhost:4445/websocket.
Therefore, update the initial part of your code,
such that it looks like this:
const wsProvider = new Web3.providers.WebsocketProvider('ws://localhost:4445/websocket');
const web3 = new Web3(wsProvider);

Setting up ejabberd via websockets

I have an ejabberd server up and running.
I can test it via web clients and it works fine using BOSH connections.
I would like to connect to it via web sockets now, and I am not sure what I am missing for it to work, I just know it doesn't.
Here is an extract from my ejabberd.yml
hosts:
- "localhost"
- "somedomain.com"
- "im.somedomain.com"
listen :
port: 5280
ip: "::"
module: ejabberd_http
request_handlers:
"/websocket": ejabberd_http_ws
"/pub/archive": mod_http_fileserver
web_admin: true
http_bind: true
## register: true
## captcha: true
tls: true
certfile: "/etc/ejabberd/ejabberd.pem"
Now I tried to open a web socket via javascript as follows :
var ws = new WebSocket("ws://somedomain:5280/websocket/");
I get ERR_CONNECTION_TIMED_OUT in return. I have nothing within ejabberd's logs when I try to open a weksocket. I do have logs of the BOSH connections.
I am not sure if I am testing appropriately, nor if my server is setup correctly.
Any suggestion is most welcome.
Connection timeout error will throw by the server when the client does not send pong response to the server make sure you are sending the pong response.If you are using Strophe.js kindly check Handlers http://strophe.im/strophejs/doc/1.2.14/files/strophe-js.html#Strophe.Connection.addHandler
connection = new WebSocket("ws://somedomain:5280/websocket/");
//Adding ping handler using strophe connection
connection.addHandler(pingHandler, "urn:xmpp:ping", "iq", "get");
//Ping Handler Call back function
function pingHandler(ping) {
var pingId = ping.getAttribute("id");
var from = ping.getAttribute("from");
var to = ping.getAttribute("to");
var pong = strophe.$iq({
type: "result",
"to": from,
id: pingId,
"from": to
});
connection.send(pong);
return true;
}
Also, consider you are adding this configuration to your ejabberd.yml
websocket_ping_interval: 50
websocket_timeout: 60

Akka HTTP not allowing incoming connections from remote hosts on macOS

I wanted to try out the following small example:
object Webserver {
def main(args: Array[String]) {
implicit val system = ActorSystem("my-system")
implicit val materializer = ActorMaterializer()
// needed for the future flatMap/onComplete in the end
implicit val executionContext = system.dispatcher
val route =
path("hello") {
get {
redirect(Uri("https://google.com"), StatusCodes.PermanentRedirect)
}
}
val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
StdIn.readLine() // let it run until user presses return
bindingFuture
.flatMap(_.unbind()) // trigger unbinding from the port
.onComplete(_ => system.terminate()) // and shutdown when done
}
}
This works perfectly when accessing from the same host on macOS. However, when I am accessing the host remotely, I can't access the akka webserver.
I have checked my Firewall options and I verified that the program java allows incoming connections.
One more suspicious thing: When I run python -m SimpleHTTPServer 8080, I get the following window:
I don't get this window when starting my akka application. Do I have to implement custom logic to ask for permission or something?
To enable remote access to your server, you need to bind your server to the external interface. To simply bind to all interfaces, you can set the host/IP to 0.0.0.0, like:
Http().bindAndHandle(route, "0.0.0.0", 8080)

No connection could be made because the target machine actively refused it 127.0.0.1:8118

trying to create web request using Tor. getting this error - "Unable to connect to the remote server".
Tor default proxy - 8118.
i have goggled for it found solution for it using Tor as Proxy but it didn't worked for me.
Code-
Process p = new Process();
p.StartInfo = new ProcessStartInfo(#"C:\Users\king\Downloads\Tor Browser\App\tor.exe", "ControlPort 9151 CircuitBuildTimeout 10");
p.Start();
Thread.Sleep(5000);
Regex regex = new Regex("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}", RegexOptions.Multiline);
do
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://whatismyipaddress.com/");
request.Headers.Add("Cache-Control", "max-age=0");
request.Proxy = new WebProxy("127.0.0.1:8118");
request.KeepAlive = false;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")))
{
string contenu = reader.ReadToEnd();
Console.WriteLine(regex.Match(contenu).Groups[0].Value);
}
}
Console.Write("en attente : continuez ?");
string line = Console.ReadLine();
if (line != "y")
break;
}
while (true);
p.Kill();
Console.ReadLine();
any idea what doing wrong in above code.
thank's
Just download the Privoxy here
the reason to run tor through privoxy is because c# does not work with socks proxies. and tor is a socks proxy, so it needs to be ran through a html proxy that runs through tor
Tor default proxy port is 8118. you have to first download privoxy here
To chain Privoxy and Tor, both running on the same system, you would use something like:
forward-socks5 / 127.0.0.1:9050
change its config to work with tor by uncommenting the above line
c# does not use sock proxies so that we have to run Tor and Provoxy at same. now you can send every web request using tor.

Resources