java.net.ConnectException : DocumentBuilder.parse(inputstream) from HttpPost - java

I am using httppost to connect to a URL which will return xml data.
StringEntity myEntity = new StringEntity(inputXMLString,"text/xml","UTF-8");
HttpPost httppost = new HttpPost(requestURL);
httppost.setEntity(myEntity);
//Set Parameter
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 1200000);
HttpConnectionParams.setSoTimeout(httpParams, 1200000);
//retrieve response
HttpClient httpClient = new DefaultHttpClient(httpParams);
InetAddress addr = InetAddress.getByName(IP_ADDRESS);
httpClient.getParams().setParameter(ConnRoutePNames.LOCAL_ADDRESS,addr);
long diff;
long start;
start = System.currentTimeMillis();
HttpResponse response = httpClient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream inputstream = entity.getContent();
diff = (start - System.currentTimeMillis());
//Then printing diff
return inputstream;
The inputstreamis used by DocumentBuilder to parse into Documnent object. It works fine in most of the cases but sometimes i get a connect exception as below
java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(Unknown
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
.................
at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)

Related

DataOutputStream os = new DataOutputStream(con.getOutputStream()); throwing connection refused exception

I am trying to post some data into the server. I am using a sample url whichis available online. I am not able to proceed further because the line,
DataOutputStream os = new DataOutputStream(con.getOutputStream());, is throwing Connection Refused Exception.
This is the code...
public static void main(String[] args) throws Exception {
try {
URL url = new URL("https://my-json-server.typicode.com/typicode/demo/posts");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
JSONObject jsonObj = new JSONObject();
jsonObj.put("id", 5);
DataOutputStream os = new DataOutputStream(con.getOutputStream());
os.writeBytes(jsonObj.toString());
os.flush();
BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream())));
int responseCode = con.getResponseCode();
String output;
StringBuffer sb = new StringBuffer();
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
sb.append(output);
break;
}
System.out.println("Response Code: "+responseCode);
System.out.println("URL: "+url);
System.out.println("Parameters: "+jsonObj.toString());
System.out.println("Output: "+output.toString());
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Below is the Exception..
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at sun.security.ssl.BaseSSLSocketImpl.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(Unknown Source)
at insertData.main(insertData.java:37)
Please help me with this. Thanks.
You need to change your BufferedReader to BufferedInputStream also the "while" loop that you have is constructed in a wrong way so far as i can see, follow the link in my previous comment

Getting connection timeout: connect

I am getting connection timeout: connect exception when I used username and password in url. url is "http://testadmin:testadmin#myhostName/manager/text/list";
This url working in chrome, firefox web browser but when i am going to access this url through java code.
Here is the output and exception I get:
&&&&&&&&&&&&&&&
*********88
response
java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at test.TomcatTest.main(TomcatTest.java:23)
I'm using the following code.
package test;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class TomcatTest {
public static void main(String[] args) {
String listUrl = "http://testadmin:testadmin#myhostName/manager/text/list";
String serverResponse = "";
URL url = null;
try {
System.out.println("&&&&&&&&&&&&&&&");
url = new URL(listUrl);
URLConnection connection = url.openConnection();
System.out.println("*********88");
// i also tried without setting readtimeout.
connection.setReadTimeout(3 * 60 * 1000);// set timeout 3 minutes
InputStream inputStream = connection.getInputStream();
System.out.println("^^^^^^^^^^^^^");
int chr = -1;
while ((chr = inputStream.read()) != -1) {
System.out.print((char)chr);
serverResponse += (char)chr;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("response " + serverResponse);
}
}
The URL http://<user>:<pass>#url is not send in this way to the web server. The Browser takes username and password away from the url and creates a basic authentication header.
Java literally sends the URL to the server. Which is a security problem, because the URL might be logged at several stages.
This demo code is 99% based on answer by Wanderson Santos and joel234 with Java 8 Base64 adaptions:
String _url_string = "http://server/"
url = new URL(_url_string);
URLConnection uc = url.openConnection();
String userpass = _user + ":" + _password;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
uc.setRequestProperty("Authorization", basicAuth);
InputStream in = uc.getInputStream();
Now I've got a solution that we can not used username and password in url like as above.
It can be used like this:
String listUrl = "http://myHostName/manager/text/list";
//use username and password here
connection.setRequestProperty("Authorization", String.format("Basic %s", new BASE64Encoder().encode("testadmin:testadmin".getBytes("UTF-8"))));

I am trying to download facebook profile picture using java.But getting error

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
public class SaveImageFromUrl {
public static void main(String[] args) throws Exception {
// proxy settings
System.setProperty("http.proxyHost", "porxyHost");
System.setProperty("http.proxyPort", "8080");
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication("userxyz","password".toCharArray()));
}
};
Authenticator.setDefault(authenticator);
String imageUrl = "https://graph.facebook.com/10000012233xxxx/picture";
String destinationFile = "D://image4.jpg";
saveImage(imageUrl, destinationFile);
}
public static void saveImage(String imageUrl, String destinationFile) throws IOException {
URL url = new URL(imageUrl);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(destinationFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
}
}
My code works fine and downloads image for other imageurl paths.But it is not working when I use String imageUrl = "https://graph.facebook.com/10000012233xxxx/picture";
I am getting the following error :
Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at sun.security.ssl.BaseSSLSocketImpl.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at SaveImageFromUrl.saveImage(SaveImageFromUrl.java:33)
at SaveImageFromUrl.main(SaveImageFromUrl.java:28)
You need to make sure that your application can follow redirects, because Facebook is sending one if you request
/{user_id}/picture
To implement this, have a look at http://www.mkyong.com/java/java-httpurlconnection-follow-redirect-example/
Also, try setting the Proxy authentication like this:
System.setProperty( "http.proxyUserName", "username" );
System.setProperty( "http.proxyPassword", "password" );
I suspect you get the timeout from your proxy connection, but you should be able to test this yourself.

Connection timed out reading and image from url

I'm trying to get an image from an url through a proxy:
URL url = new URL("https://www.google.es/images/srpr/logo11w.png"); //Example
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy", 8080)); //Proxy address is http://proxy:8080
URLConnection conexión = url.openConnection(proxy);
conexión.connect();
Image imagen = ImageIO.read(url.openStream());
The problem is at this.imagen = ImageIO.read(url.openStream());:
java.net.ConnectException: Connection timed out: connect
at java.net.TwoStacksPlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at sun.security.ssl.BaseSSLSocketImpl.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at gui.Ventana.<init>(Ventana.java:34)
at servicio.Servicio2.buscar(Servicio2.java:60)
at data.Main.main(Main.java:20)
I have also tried using the Authenticator class adding Authenticator.setDefault(new Autenticador(username, password));
public class Autenticador extends Authenticator {
private String usuario;
private String password;
public Autenticador(String usuario, String password) {
this.usuario = usuario;
this.password = password;
}
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(usuario, password.toCharArray());
}
}
}
And I still get the same error. Any suggestion? Thanks.

Twitter4j, Unknown Host exception

I try to operate the basic functions of twitter4j to train me on this library. My first test is to retrieve my timeline is one of the first tutorials on the site twitter4j.
Here's my code to retrieve my timeline :
String accessToken = "***";
String accessSecret = "***";
String consumerKey = "***";
String consumerSecret = "***";
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(consumerKey)
.setOAuthConsumerSecret(consumerSecret)
.setOAuthAccessToken(accessToken)
.setOAuthAccessTokenSecret(accessSecret);
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
List<Status> statuses = twitter.getHomeTimeline();
System.out.println("Showing home timeline.");
for (Status status : statuses) {
System.out.println(status.getUser().getName() + ":" +
status.getText());
}
But with this simple code, I have the following error :
Exception in thread "main" api.twitter.com
Relevant discussions can be found on the Internet at:
http://www.google.co.jp/search?q=e5488403 or
http://www.google.co.jp/search?q=09b41b1e
TwitterException{exceptionCode=[e5488403-09b41b1e 6ece33f2-2ccf4468], statusCode=-1, message=null, code=-1, retryAfter=-1, rateLimitStatus=null, version=3.0.3}
at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:192)
at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:61)
at twitter4j.internal.http.HttpClientWrapper.get(HttpClientWrapper.java:81)
at twitter4j.TwitterImpl.get(TwitterImpl.java:1835)
at twitter4j.TwitterImpl.getHomeTimeline(TwitterImpl.java:117)
at Test.main(Test.java:32)
Caused by: java.net.UnknownHostException: api.twitter.com
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at twitter4j.internal.http.HttpResponseImpl.<init>(HttpResponseImpl.java:34)
at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:156)
... 5 more
Where is the problem ?
Finally, I got my problem, the code was perfect but i have a proxy. So I fixed it :
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(consumerKey)
.setOAuthConsumerSecret(consumerSecret)
.setOAuthAccessToken(accessToken)
.setOAuthAccessTokenSecret(accessSecret)
// PROXY
.setHttpProxyHost(proxyHost)
.setHttpProxyPort(proxyPort)
;

Categories

Resources