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
Related
i tried to get view source(html page) from websit
i used whit this code
public static void main(String[] args) {
URL url;
InputStream is = null;
BufferedReader br;
String line;
try {
url = new URL("http://stackoverflow.com/");
is = url.openStream(); // throws an IOException
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (is != null) is.close();
} catch (IOException ioe) {
// nothing to see here
}
}
}
and when i bring to line "is = url.openStream();
i received exception "java.net.UnknownHostException"
java.net.UnknownHostException: stackoverflow.com
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 java.net.URL.openStream(Unknown Source)
at test.main.main(main.java:17)
do you know how i can fix this code
thanks a lot,
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"))));
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.
I am trying to get response from below REST api. when I open that URL in browser, I gets xml repsonse from server. but when I am trying to get the same using java program I am getting below exception
IOEXCeption
java.net.UnknownHostException: rxnav.nlm.nih.gov
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 java.net.HttpURLConnection.getResponseCode(Unknown Source)
at com.test.demo.RestConnector.run(RestConnector.java:22)
at java.lang.Thread.run(Unknown Source)
Pls help me regarding this
below is the code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class RestConnector implements Runnable{
#Override
public void run() {
String URLString = "http://rxnav.nlm.nih.gov/REST/classes?src=MESH";
try {
URL url = new URL(URLString);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
if(connection.getResponseCode() != 200){
System.out.println("Failed to connect:"+connection.getResponseCode());
System.out.println("Response Message:"+connection.getResponseMessage());
}
System.out.println("I am here ");
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line ;
while((line = reader.readLine()) != null){
System.out.println(line);
}
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOEXCeption");
e.printStackTrace();
}
}
public static void main(String[] args) {
Thread t = new Thread(new RestConnector());
t.start();
}
}
1) The error clearly says "can't resolve hostname".
2) Q: Does your AndroidManifest.xml grant Internet permissions? Make sure it contains this line:
<uses-permission android:name="android.permission.INTERNET" />
3) Q: is this a real device, or an emulator? If the latter, consider recreating your AVD. Believe it or not, that can sometimes help: Android java.net.UnknownHostException: Host is unresolved.
4) Finally, here are some other tips - including proxy server configuration - that might help:
http://eliasbland.wordpress.com/2011/02/22/java-net-unknownhostexception-on-android-a-list-of-possible-causes/
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)