How to check if proxy is working in Java? - java

I searched google, this site and JavaRanch and I can not find an answer.
My program needs to obtain proxies from a selected file(I got that done using java gui FileChooser class and RandomAccessFile)
Then I need to verify the proxies starting with the one that is first in the txt file. It will try to connect to some site or port to verify if the connection was successful.If the connection was successful (I got a positive response) it will add the proxy to a list of proxies and then get and check next one in the list until it is done.
I know how to do this but I got a little problem. My Problem is that this process needs to be independent of connection speed because someone may set 15000(milliseconds) timeout for the connection to be dealt with and set 100 threads and then none of the proxies would come out working because connection is too slow.
I heard of a method called pinging to check proxies,but I do not know how to use it in java.
Could anyone give me solution or at least classes I could use.

Ok I found a solution and it is easy.
What I used it InetAddress.isReachable() method along with some HttpClient by Apache. For proxy checking I used blanksite.com because all I need is check connectability and not speed of proxies.
So here is the code(Including input from file, but it is not gui, YET):
/* compile with
java -cp .;httpclient-4.5.1.jar;httpcore-4.4.3.jar ProxyMat
run with
java -cp .;httpclient-4.5.1.jar;httpcore-4.4.3.jar;commons-logging-1.2.jar ProxyMat
put one proxy to check per line in the proxies.txt file in the form
some.host.com:8080
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.net.InetAddress;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
public class ProxyMat{
File file=null;
static RandomAccessFile read=null;
public ProxyMat(){
file=new File("proxies.txt");
try {
read=new RandomAccessFile(file,"rw");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void checkproxies(){
try{
String line;
for(int i=0;i<25;i++){
if((line=read.readLine())!=null){
System.out.println(line);
String[] hp=line.split(":");
InetAddress addr=InetAddress.getByName(hp[0]);
if(addr.isReachable(5000)){
System.out.println("reached");
ensocketize(hp[0],Integer.parseInt(hp[1]));
}
}
}
}catch(Exception ex){ex.printStackTrace();}
}
public void ensocketize(String host,int port){
try{
File pros=new File("working.txt");
HttpClient client=new DefaultHttpClient();
HttpGet get=new HttpGet("http://blanksite.com/");
HttpHost proxy=new HttpHost(host,port);
client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 15000);
HttpResponse response=client.execute(get);
HttpEntity enti=response.getEntity();
if(response!=null){
System.out.println(response.getStatusLine());
System.out.println(response.toString());
System.out.println(host+":"+port+" ## working");
}
}catch(Exception ex){System.out.println("Proxy failed");}
}
public static void main(String[] args){
ProxyMat mat=new ProxyMat();
mat.checkproxies();
}
}

Related

How to listen and generate respones for client in server in java?

This is my server side code in java listening on port 1880 and making http client request from browser/client.java code in localhost which gives connection refused error.I copied that server code from a webpage.I am not sure what exactly this code is doing.
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerHandlingHttpRequest {
public void start() throws IOException
{
InetSocketAddress addr=new InetSocketAddress(1880);
System.out.println(addr.getPort());
System.out.println(addr.getAddress());
System.out.println(addr.getHostName());
System.out.println(addr.toString());
HttpServer server=HttpServer.create(addr,0);
server.createContext("/", new MyHandler());
server.setExecutor(null);
server.start();
System.out.println("Server Listening");
System.out.println(server.getAddress());
server.stop(60);
}
class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
System.out.println("Request Arrived");
String response = "This is the response";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
public static void main(String[] args) throws IOException
{
ServerHandlingHttpRequest w=new ServerHandlingHttpRequest();
w.start();
}
}
That code simply starts listening to the port that you have specified, as an HTTP listener. Which means, any HTTP Request that might come into that port will be intercepted by your program. And when it intercepts, it looks for the context path that you have configured to handle the response to the request.
So, when you run this program, it starts listening at port 1880. When a URL http://localhost:1880/ is hit, it will be intercepted by the handler, MyHandler. The response will be written to the OutputStream which will send back the request back to the client.
One of the problems that I see is that you are stopping the server after printing some statements, while the example that you have refered is not doing so. May be, remove server.stop(60) statement and check whether the issue still persists.

SSLPeerUnverifiedException (Unirest)

I'm new to messing around with APIs (both official and unofficial) and I'm using one called JavaSnap. I've been messing around with a very basic implementation of the example code, but have been running into errors. Here is the very basic code:
Snapchat snapchat = Snapchat.login("xxxx", "xxxxx");
Firstly I ran into loads of ClassNotFound errors and had to keep on downloading apache modules (commons, httpcomponents etc.) to allow the program to progress, but being class files this meant I couldn't see all at once what modules I needed to download. So if anyone wants to tell me how wrong I'm doing something feel free.
Anyway, now having cleared up all the ClassNotFound exceptions (I hope) I'm getting the following exception:
com.mashape.unirest.http.exceptions.UnirestException: javax.net.ssl.SSLPeerUnverifiedException: Host name 'feelinsonice-hrd.appspot.com' does not match the certificate subject provided by the peer (CN=*.appspot.com, O=Google Inc, L=Mountain View, ST=California, C=US)
at com.mashape.unirest.http.HttpClientHelper.request(HttpClientHelper.java:146)
at com.mashape.unirest.request.BaseRequest.asJson(BaseRequest.java:68)
at com.habosa.javasnap.Snapchat.requestJson(Snapchat.java:953)
at com.habosa.javasnap.Snapchat.login(Snapchat.java:160)
at Tester.go(Tester.java:21)
As I understand it, this is because I need to enable trusting all certificates, however to do this I believe I'd need to use HostNameVerifiers with SSLSocketFactorys, but I can't really begin to mess around with this as I only have the source for the JavaSnap API, and tracing the error up the stack the most recent method available for me to edit is this:
private static HttpResponse<JsonNode> requestJson(String path, Map<String, Object> params, File file) throws UnirestException {
MultipartBody req = prepareRequest(path, params, file);
// Execute and return response as JSON
HttpResponse<JsonNode> resp = req.asJson();
// Record
lastRequestPath = path;
lastResponse = resp;
lastResponseBodyClass = JsonNode.class;
return resp;
My question is, am I actually on the right lines with my thinking? If I am how can I achieve my goal of eliminating this error / trusting certificates? If I'm not then what in fact is the problem?
Thanks very much
i answer this old question to remember my search
the certificate error solution is a combination from a few places
https://github.com/Mashape/unirest-java/issues/70, where i started.
http://literatejava.com/networks/ignore-ssl-certificate-errors-apache-httpclient-4-4/ very good explanation.
http://www.baeldung.com/httpclient-ssl, solution for all versions.
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext;
import javax.security.cert.CertificateException;
import javax.security.cert.X509Certificate;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
public class XXX {
private static HttpClient unsafeHttpClient;
static {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
unsafeHttpClient = HttpClients.custom().setSSLContext(sslContext)
.setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
e.printStackTrace();
}
}
public static HttpClient getClient() {
return unsafeHttpClient;
}
public static void main(String[] args) {
try {
HttpClient creepyClient = RestUnirestClient.getClient();
Unirest.setHttpClient(creepyClient);
HttpResponse<JsonNode> response = Unirest.get("https://httpbin.org/get?show_env=1").asJson();
System.out.println(response.getBody().toString());
} catch (UnirestException e) {
e.printStackTrace();
}
}
}

Is possible to call servlet from applet

I am not familiar with java and applets, so any one please let me know the possibilities for the following my questing.
I would like to call the Servlet from applet.. is this possible?
If the 1st one is possible can we store the Servlet output like XML data or string in the applet variable?
If the 2nd one is possible, then can get that that variable value using JavaScript or J Query?
If possible please give me the simple example.
Thanks in advance.
Yes you can. The servlet exposes a URL, which you can get with the help of the URLConnection class.
Again you can do this, see here on how you can use the URL connection.
You can do that too, create an applet to get the applet field, and look here on how you can invoke the method.
But all these sound awfully complicated. Why don't you tell us what you are trying to achieve, maybe there is a simpler way to do things.
One : yes you can call the servlet from applet making http calls
step 1 : make a http call to your servlet
step 2 : make your servlet return XML response
step 3 : parse xml response
using this program you can make a call to your servlet
package com.hussain;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class callServlet {
public static void main(String[] args)
{
String servletResponse = callServlet.sendRequest("http://gdata.youtube.com/feeds/base/videos?max-results=10&start-//index=1&alt=json&orderby=published&author=astrobixweb");
callServlet.parseFromXMLResponse(servletResponse);
}
public static String sendRequest(String url) {
String result = "";
try {
HttpClient client = new DefaultHttpClient();
HttpParams httpParameters = client.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpConnectionParams.setTcpNoDelay(httpParameters, true);
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
InputStream ips = response.getEntity().getContent();
BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));
StringBuilder sb = new StringBuilder();
String s;
while (true) {
s = buf.readLine();
if (s == null || s.length() == 0)
break;
sb.append(s);
}
buf.close();
ips.close();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void parseFromXMLResponse(String respo)
{
// parse your XML response here
}
}
Moving in the flow of your question,
You may call the servlet from your applet:
Construct the url that will hit your servlet.
Use java.net.URLConnection object to hold the connection from your appletURLConnection con = urlToServlet.openConnection()
'con.setDoOutput(true)' => Application intends to write data to the URL connection.
Use the input and output streams to communicate with the Servlet.
con.getInputStream() and con.getOutputStream()
[Note: Don't forget to close all the connections and streams]
Now, use the data you obtained from the InputStream, in what so ever form you want.
Its extreamly simple, use this code:
In Applet:
public String getYourString(){ return responseFromServlet;}
In Javascript:
var jsResp = document.name_of_your_applet.getYourString();
Hope, you've got your answers!

Can't Send File using TFTPClient (Apache Commons Net library)

I am trying to create TFTPClient using Apache Commons Net to put file on Server (AIX OS) and TFTP service is running on that Server, there isn't any exception raised while running the below code and it seems that everything is ok, but the file didn't put on the server.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.SocketException;
import java.net.UnknownHostException;
import org.apache.commons.net.tftp.TFTP;
import org.apache.commons.net.tftp.TFTPClient;
public class Test {
/**
* #param args
* #throws IOException
* #throws SocketException
*/
public static void main(String[] args) throws SocketException, IOException {
int timeout=5000;
String host="192.168.1.20";
int port=22;
TFTPClient tftpClient=new TFTPClient();
tftpClient.setDefaultTimeout(60000);
tftpClient.open(69);
tftpClient.setSoTimeout(timeout);
System.out.println("DONE");
FileInputStream input = null;
File file;
file = new File("D:\\project.ear");
input = new FileInputStream(file);
try{
tftpClient.sendFile("/home/dev/project.ear", TFTP.BINARY_MODE, input, host);
}
catch (UnknownHostException e)
{
System.err.println("Error: could not resolve hostname.");
System.err.println(e.getMessage());
System.exit(1);
}
System.out.println("DONE2");
tftpClient.close();
}
}
the output of the above code was:
DONE
DONE2
which means that everything is OK but i didn't find the file in the directory specified in code.
please advice.
If you still need help, I think you should try call tftpClient.sendFile method this way:
tftpClient.sendFile("/home/dev/project.ear", TFTP.BINARY_MODE, input, InetAddress.getByName(host));
While using InetAddress.getByName(host) it should determine your host ip address either by ip string representation or hostname, as it says here. Hope it works this way.

Android Simple HTTP Request?

I have this code for an Android application I'm trying to create into interact with my PHP website. I have the android.permission.INTERNET permission activated and it keeps creating a toast that says "ERROR." instead of the contents of the website. Here is my only java file:
package com.http.request;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class HttprequestActivity extends Activity {
/** Called when the activity is first created. */
private String doHTTPRequest(String url){
String results = "ERROR";
try
{
HttpClient hc = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
HttpResponse rp = hc.execute(post);
if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
results = EntityUtils.toString(rp.getEntity());
}
}catch(IOException e){
e.printStackTrace();
}
return results;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String results = doHTTPRequest("http://www.yahoo.com");
Toast.makeText(getApplicationContext(), results, Toast.LENGTH_LONG).show();
}
}
I would check to make sure that,
If there is an exception being thrown, investigate what is causing the IOException
Your server could potentially be returning a non-200 response code.
Put in some breakpoints and see whats happening there. My bet is on the response code.
That is your own "ERROR" string which the Toast() displays. Better change
catch(IOException e){
e.printStackTrace();
}
to
catch(IOException e){
result = "ERROR IOException";
e.printStackTrace();
}
The exception is thrown as you try to connect in the main thread which is not permitted. Put doHTTPRequest() in a thread or AsyncTask.
What is your stacktrace says, LogCat? What is the error? Add more info, make it more clear to understand than "guessing of coffee beans"
My guess is: this happens because you are trying to do network operation in UI thread which is not allowed in 3.0+ versions.
http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

Categories