I need to set source IP address (for something like IP Spoofing) before sending out an http request. Class used for setting up http connection is HTTPURLConnection. I found below link on stackoverflow which is really useful.
Registering and using a custom java.net.URL protocol
As in the post, I have already created 3 classes extending URLConnection , URLStreamHandler and implementing URLStreamHandlerFactory. This looks to be working fine; however I am getting exception which I think is because I have not implemented getInputStream for URLConnection as was mentioned in above post.
I have couple of questions
1> I am extending custom URLConnection class from HTTPURLConnection, so what's the need of implementing getInputStream as anyway it's a virtual method
2> If I have to do it, can someone provide sample implementation of this method?
JMeter already provides the IP Spoofing feature.
In Http Request Defaults, select (in version 3.0 of JMeter) advanced tab :
See http://jmeter.apache.org/usermanual/component_reference.html#HTTP_Request_parms1:
Source address field
[Only for HTTP Request with HTTPClient implementation]
This property is used to enable IP Spoofing. It overrides the default local IP address for this sample. The JMeter host must have multiple IP addresses (i.e. IP aliases, network interfaces, devices). The value can be a host name, IP address, or a network interface device such as "eth0" or "lo" or "wlan0".
If the property httpclient.localaddress is defined, that is used for all HttpClient requests.
Based on UBIK LOAD PACK's answer. Here is the same code using Aapche http client 3.x. (The variable for setting source IP is args[1])
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.protocol.Protocol;
public class HC3Test {
public static void main(String[] args) throws Exception {
String url = args[0];
java.net.URL uri = new java.net.URL(url);
HostConfiguration hc = new HostConfiguration();
hc.setHost(uri.getHost(), uri.getPort(), Protocol.getProtocol(uri.getProtocol()));
hc.setLocalAddress(java.net.InetAddress.getByName(args[1]));//for pseudo 'ip spoofing'
HttpClient client = new HttpClient(new SimpleHttpConnectionManager());
client.setHostConfiguration(hc);
GetMethod method = new GetMethod(url);
client.executeMethod(method);
method.releaseConnection();
}
}
Sample code for http client 4.x:
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
public class HC4Test {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpClient = new DefaultHttpClient();
org.apache.http.params.HttpParams params = httpClient.getParams();
params.setParameter(ConnRoutePNames.LOCAL_ADDRESS,
java.net.InetAddress.getByName(args[1]));//for pseudo 'ip spoofing'
httpClient.execute(new HttpGet(args[0]));
}
}
To accomplish to have a different source address via an http request you could use a local proxy.
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
public class Huhu {
public static void main(String[] args) throws IOException {
URL url = new URL("http://google.com");
Proxy proxy = new Proxy(Proxy.Type.DIRECT,
new InetSocketAddress(
InetAddress.getByAddress(
new byte[]{your, ip, interface, here}), yourTcpPortHere));
URLConnection conn = url.openConnection(proxy);
}
}
You do not have to override anything this way.
Related
I have a WSDL file which I've turned into Java code by using WSDL2Java inside SoapUI, it works fine, but now I need to add my company's proxy to it, so every SOAP http request would go through it (but not other http requests).
I've looked through multiple threads concerning the same issue and found these options:
system wide proxy by adding
System.getProperties().put("proxySet", "true");
System.getProperties().put("https.proxyHost", "10.10.10.10");
System.getProperties().put("https.proxyPort", "8080");
which doesn't work for me, since it affect the whole jvm.
adding the following code
HelloService hello = new HelloService();
HelloPortType helloPort = cliente.getHelloPort();
org.apache.cxf.endpoint.Client client = ClientProxy.getClient(helloPort);
HTTPConduit http = (HTTPConduit) client.getConduit();
http.getClient().setProxyServer("proxy");
http.getClient().setProxyServerPort(8080);
http.getProxyAuthorization().setUserName("user proxy");
http.getProxyAuthorization().setPassword("password proxy");
which I don't get how to use. My generated code doesn't have any traces of org.apache.cxf, only javax.xml.ws.
Adding this to my port configuration:
((BindingProvider) port).getRequestContext().put("http.proxyHost", "proxy#example.com");
((BindingProvider) port).getRequestContext().put("http.proxyPort", "80");
Here I use a random non-existing proxy and expect to get an error of any sort(timeout, invalid proxy, etc.), but instead it goes through without any errors.
Here is an example without using 3rd party libraries.
https://github.com/schuch/jaxws-proxy-example/blob/master/jaxws-client-with-proxy/src/main/java/ch/schu/example/helloworld/Client.java
package ch.schu.example.helloworld;
import java.net.ProxySelector;
import ch.schu.example.hello.HelloImpl;
import ch.schu.example.hello.HelloImplService;
public class Client {
public static void main(String[] args) {
ProxySelector.setDefault(new MyProxySelector());
HelloImplService service = new HelloImplService();
HelloImpl hello = service.getHelloImplPort();
System.out.println(hello.sayHello("Howard Wollowitz"));
}
}
https://github.com/schuch/jaxws-proxy-example/blob/master/jaxws-client-with-proxy/src/main/java/ch/schu/example/helloworld/MyProxySelector.java
package ch.schu.example.helloworld;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.*;
import java.util.*;
public class MyProxySelector extends ProxySelector {
#Override
public List<Proxy> select(URI uri)
{
System.out.println("select for " + uri.toString());
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 9999));
ArrayList<Proxy> list = new ArrayList<Proxy>();
list.add(proxy);
return list;
}
#Override
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
System.err.println("Connection to " + uri + " failed.");
}
}
I am trying to downloada picture from a certain url, but cant do so because I somehow have to give the right userclient to the website.I am sure the problem is that I cant give the user client while using the Url class, because the page can be accesed via browser. I tried using proxy and Urlconnection but couldnt get it to work. Please share your toughts on the matter!
My code is the following:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.URL;
import java.net.URLConnection;
import javax.imageio.ImageIO;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.highgui.Highgui;
public class KepLetolto {
public static void main(String[] args) throws IOException {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
File file = new File("tempjpeg");
SocketAddress address = new java.net.InetSocketAddress("xyz.com", 8080);
// Create an HTTP Proxy using the above SocketAddress.
Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
URL url_kep =new URL("http://www.theouthousers.com/images/templates/thumbnails/128058/bayfinger_size3.png");
ImageIO.write(ImageIO.read(url_kep), "jpeg", file);
Mat uj = Highgui.imread("temp.jpeg" ,Highgui.CV_LOAD_IMAGE_COLOR);
}
}
Instead of using ImageIO.read(URL), which limits you to the default behavior of the URL's underlying URLConnection, use ImageIO.read(InputStream).
This allows you to use any HTTP client library - including the basic HttpURLConnection, which you can get from (HttpURLConnection)url_kep.openConnection(). Using that, you can set headers such as User-Agent, if that's the header required by the site, or other headers such as Referer which are sometimes used to prevent deep-linking.
Once you set up all the headers and any other request options, you can get an InputStream from the client object, and pass that to ImageIO.
This Solution Worked For Me:
URLConnection openConnection = new URL("YOUR_IMAGE_URL").openConnection();
openConnection.addRequestProperty("User-Agent", "YOUR USER AGENT");
InputStream is = openConnection.getInputStream();
BufferedImage saveImage = ImageIO.read(is);
ImageIO.write(saveImage, "png", new File("PATH\\TO\\IMAGE\\FILE.PNG"));
In Java, is it possible to view multiple response headers on a HttpURLConnection if they have the same name?
In the Oracle documentation for "GetHeaderField", it states:
If called on a connection that sets the same header multiple times
with possibly different values, only the last value is returned.
My question is, how do I view all the different values for a header that is set multiple times?
Use getHeaderFields
List<String> values = conn.getHeaderFields().get("X-Header-Of-Interest");
Complete example
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
public class UrlConnectionTest {
public static void main (String[] args) throws IOException {
URL url = new URL("http://localhost:8888/");
URLConnection conn = url.openConnection();
conn.getContent(); // Force request
System.out.println(conn.getHeaderFields().get("X-Funky-Header"));
}
}
On Linux you can create a simple single-request server with netcat for testing
$ echo -e 'HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nX-Funky-Header: value1\r\nX-Funky-Header: value2\r\n\r\nContent' | nc -l 8888 &
Hi, I want to pass the username and password to connect to localhost where I have deployed memcached.
Here is my code.
import java.io.IOException;
import java.net.InetSocketAddress;
import net.spy.memcached.MemcachedClient;
public class MemCaheConnection {
public void ConnectMemCaheConnection() throws IOException{
MemcachedClient c = new MemcachedClient(new InetSocketAddress("localhost", 11211));
c.flush();
}
}
Can anyone help?
without explicit use of http://code.google.com/p/memcached/wiki/SASLAuthProtocol there is no need for username+password, did you check the service is running on port 11211?
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();
}
}