java.net.SocketException: Connection reset when connection time out >0 - java

I am calling an api to send sms with a java apache common client, and it looks like setting a time out for more than 0 is returning a "java.net.SocketException: Connection reset" error.
Here is a the code sample
// creating the http client
HttpClient client = new HttpClient();
Setting a connection time out of 10 sec (I receive a successful response
as soon as I remove this part of the code)
client.getHttpConnectionManager().
getParams().setConnectionTimeout(10000);
Rest of the code
//creating the request method
GetMethod method = new GetMethod(smsUrl);
// setting its params
method.setQueryString(new NameValuePair[] {
new NameValuePair("username", user),
new NameValuePair("password", pass),
new NameValuePair("action", "sendsms"),
new NameValuePair("from", "Woosh"),
new NameValuePair("to", toMobile),
new NameValuePair("text", textBody)
});
//calling the method
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
int statusCode = client.executeMethod(method);

The issue was sorted out, it was an issue caused by the server of the api I was calling. Not sure what was it though

Related

JAVA run multiple linked classes

I need to run different linked classes in java.
• The main one : Robot.java
• The second one : Request.java
I simulate a remote (with a TCP server) which controls Request which is a TCP client.
When Request received an information from the TCP server, it is stocked in String req.
I need to access req from Robot to decode and execute the request.
Thus in the Robot's constructor I do :
Request r = new Request("My robot");
r.setServer()
setServer() contains :
try{
socket = new Socket(IP, PORT);
System.out.println(socket);
out = new PrintWriter(socket.getOutputStream(), true);
out.println("NewRobot:"+getRobotName()); //Send the information that I'm creating a new robot !
String message ;
do {
in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()
)
);//get response from server
message = in.readLine() ;
System.out.println(message);
setReq(message); // Message always contains the request, so I set the request var
}while(!message.matches("^.*STOP.*$"));
in.close();
out.close();
socket.close();
} catch (Exception e) {
System.err.println(e);
System.exit(1);
}
The problem is when I do r.setServer() Robot.java runs while(!message.matches("^.*STOP.*$");
So the rest of the program is executed only when Request receive STOPwhile I need to access to each received request.
To access to this request I thought I could use a Timer in Robot, so each 100ms it calls r.getReq() to execute it.
What could I do to execute both classes with letting them linked as they are ?
Thanks, Lucas ^

How do I send a json object from Android app to a web service written in C#?

I'm trying to send a json object from my Android code to a webservice written in C# but could not invoke the webservice. I've setup a private network to which my system which is running webservice and android phone which is running android code are connected. To check whether webservice ever gets invoked, I installed a rest client on my phone and did a post, the break point in webservice got a hit. But when I try from my android code, I was able to setup a connection and when I write json object it waits as if it is writing. The breakpoint in webservice never gets a hit from android code. Below is my android code:
Collection<JSONObject> items = new ArrayList<JSONObject>();
JSONObject field = new JSONObject();
String base64String = Base64.encodeToString(image_in_byte,
Base64.DEFAULT);
File filename = new File(Directory1 + "/" +
file.getName());
String file_str = file.getName();
field.put("ID", file_str);
field.put("Flag", "true");
field.put("Image", base64String);
field.put("Type", "JPEG" );
items.add(field);
UUID uid = UUID.randomUUID();
String u_string = uid.toString();
JSONObject temp = new JSONObject();
temp.put("field1", u_string);
temp.put("field2", "ABCD");
temp.put("field3", items);
HttpURLConnection rc;
String SERVER = "webservice url";
URL url = new URL(SERVER);
rc = (HttpURLConnection)url.openConnection();
try
{
rc.setDoOutput(true);
rc.setDoInput(true);
rc.setUseCaches(false);
rc.setRequestMethod("POST");
rc.setRequestProperty("Connection", "Keep-Alive");
rc.setRequestProperty("Content-Type", "application/json; charset=utf-8");
rc.setRequestProperty("Accept", "application/json; charset=utf-8");
rc.setConnectTimeout(timeout);
rc.setReadTimeout(0);
rc.connect();
OutputStream out = new BufferedOutputStream(rc.getOutputStream());
out.write(temp.toString().getBytes());
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
finally
{
rc.disconnect();
}
rc.connect() seems to be establishing the connection as the "connected" field in rc is true. temp above is the json object which I want to send to the webservice, the write operation waits, it seems to be writing but the webservice never gets a hit. I dont know why it is not working, any help in this direction is very much appreciated.
Thanks.

how does httpclient 4.3 default timeout setting work, if not setting connectiontimeout, connectionmanagertimeout, and sockettimeout?

I have recently used httpclient 4.3, I know api has been changed, but if not setting timeout threshold(conenction or socket or conenctionmanager), it can work, which means no infinite loop query, and method.getResponseBodyAsString() would return an empty string, but in the document, it said that default parameter setting of timeout is infinite, so how does it work?
public class ContentModelUtils {
private static HttpClient client = new HttpClient();
...
public static String fetchPlainHttpResult(String id, Map<String, String> result, String getUrl)
throws HttpException, IOException {
method = new GetMethod(fetchPlainUrl(id, result, getUrl));
//client.getParams().setParameter("http.socket.timeout",1000);
//client.getParams().setParameter("http.connection.timeout",1000);
//client.getParams().setParameter("http.connection-manager.timeout",10000L);
client.executeMethod(method);
if (method.getStatusCode() != 200) {
return null;
}
String outputValue = new String(method.getResponseBodyAsString());
return outputValue;
}
...
The default setting is in fact an infinite timeout. To prove this, let's browse the source repository for Apache HttpCore 4.3.x.
In BasicConnFactory, we can see it pulling the connect timeout setting, and the line of code that retrieves the timeout parameter uses a default of 0.
this.connectTimeout = params.getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 0);
Later, in BasicConnFactory#create, this timeout value is passed into a socket connection.
socket.connect(new InetSocketAddress(hostname, port), this.connectTimeout);
According to the documentation of Socket#connect, a timeout value of 0 (which we saw earlier is the default) is interpreted as an infinite timeout.
Connects this socket to the server with a specified timeout value. A timeout of zero is interpreted as an infinite timeout. The connection will then block until established or an error occurs.

What is the meaning of "per route basis" in PoolingClientConnectionManager?

ThreadSafeClientConnManager is deprecated and a new method is introduced PoolingClientConnectionManager.
The documentation of PoolingClientConnectionManager says
Manages a pool of client connections and is able to service connection
requests from multiple execution threads. Connections are pooled on a
per route basis.
My Question
What is the meaning of per route basis here?
Put it in simple term, per route means per host you are connecting to.
PoolingHttpClientConnectionManager maintains a maximum limit of connections on a per route basis and in total. Per default this implementation will create no more than 2 concurrent connections per given route and no more 20 connections in total.
It refers to the HttpRoute. The HttpRoute is to delineate multiple applications running on the same web server.
http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/conn/routing/HttpRoute.html
It is used like below:
ClientConnectionRequest connRequest = connMrg.requestConnection(
new HttpRoute(new HttpHost("localhost", 80)), null);
ManagedClientConnection conn = connRequest.getConnection(10, TimeUnit.SECONDS);
try {
BasicHttpRequest request = new BasicHttpRequest("GET", "/");
conn.sendRequestHeader(request);
HttpResponse response = conn.receiveResponseHeader();
conn.receiveResponseEntity(response);
HttpEntity entity = response.getEntity();
if (entity != null) {
BasicManagedEntity managedEntity = new BasicManagedEntity(entity, conn, true);
// Replace entity
response.setEntity(managedEntity);
}
// Do something useful with the response
// The connection will be released automatically
// as soon as the response content has been consumed
} catch (IOException ex) {
// Abort connection upon an I/O error.
conn.abortConnection();
throw ex;
}
source: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html

Automating password checking using httpclient

Right now I'm having some major issues with writing a simple portscanner / password checker for a work security project.
My basic goal is to write a quick little tool that opens up a text file, Scans on ports 21,23,80,502, and 8080 then simply writes the returned http status to a file (200, 404, whatever)
So far I've been trying to do this using httpclient and I've had very poor results.
My code goes something like this
public static void doHosts() throws Exception{
String filename = "C:\\test.txt";
String ip = "";
String port[] = {"21", "23", "80", "502", "8080"};
FileInputStream fstream = new FileInputStream("c:\\scan.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while ((ip = br.readLine()) != null) {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
int timeoutSocket = 5000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpHost targetHost = new HttpHost(ip);
DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
UsernamePasswordCredentials creds = new UsernamePasswordCredentials("blah", "blah");
httpclient.getCredentialsProvider().setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), creds);
NegotiateSchemeFactory nsf = new NegotiateSchemeFactory();
httpclient.getAuthSchemes().register(AuthPolicy.SPNEGO, nsf);
// 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
BasicHttpContext localcontext = new BasicHttpContext();
localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
httpclient = wrapClient(httpclient);
HttpGet get;
for (int i = 0; i < port.length; i++) {
get = new HttpGet("http://" + ip + ":" + port[i] + "/");
HttpResponse response = httpclient.execute(get);
try {
BufferedWriter out = new BufferedWriter(new FileWriter("filename", true));
out.write("ip: "+ ip + " : "+port+ " - " + response.getStatusLine().getStatusCode()); //HTTP status returned off request );
} catch (IOException e) {
}
}
}
}
My issue thus far has been that it opens the text file, hits a single bad result, doesn't serialize it, then just dies with an exception.
I'm not sure how to make it continue with an exception (I know some sites will say "not up" that's why it's a port scanner.
Any help would be wonderful and would probably save some poor interns from manually checking about 6000 ip's tomorrow.
You are not handling exceptions thrown by HttpClient when the connection cannot be made. You should not assume that httpclient.execute(get) will always return without exception.
If you want your program to ignore these conditions and keep on trucking, you need to catch these exceptions.
Alternatively, it seems like you might want to give nmap a try.
You don't say in your post, but my guess is it's throwing ClientProtocolException on the first request to port 21, which is to be expected as port 21 does not speak HTTP. You are not catching this exception, so your program dies.
What do you mean by "bad results"? Cases where nmap said a port was open or closed and it wasn't?
If you do decide to continue down the nmap path and want to integrate nmap with some Java code, have a look at Nmap4j on sourceforge.net. It's a simple Java wrapper around Nmap that allows you to access the results as Java objects.

Categories