Getting Network is unreachable on IPV6 Network - java

I am getting "Network is Unreachable" from below Java Http request for any url.
Below code is working fine with IPV4 network.
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Please help me on this issue.

If you are specifying the IPv6 URL using the IP address, you need to enclose it in square brackets since the :: in the address are special characters in a URL.
See RFC 2732.

Related

can't reset method:already connected error at rest get service

I know this question has been asked many times I am writing it because I could not see an exact answer for that question. When I use following get service I get "java.net.ProtocolException: Can't reset method: already connected".
You can see the snippted below. For privacy reasons , I cannot share the get request link.
Thank you guys
try {
URL url = new URL("https://......");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() == 200) {
return true;
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Connection to distant server using HttpURLConnection

I try to send a json object to a distant server using HttpURLConnection.
but this error was displayed
"Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 401
at TestSendSMS.main(TestSendSMS.java:40)"
I didn't know what's the problem.What's wrong in this code? Any help
try {
/*
* JSONObject jsonParam = new JSONObject();
* jsonParam.put("-----","----"); jsonParam.put("----","-----");
* jsonParam.put("-----","-----");
*/
String input = "{\"------\":\"------\",\"-----\":\"------\",\"------\":\"-----\"}";
System.out.println("JsonObj " + jsonParam);
URL myURL = new URL("-----------------------");
HttpURLConnection myURLConnection = (HttpURLConnection) myURL
.openConnection();
myURLConnection.setDoOutput(true);
myURLConnection.setDoInput(true);
myURLConnection.setChunkedStreamingMode(0);
myURLConnection.setUseCaches(false);
myURLConnection.setConnectTimeout(10000);
myURLConnection.setReadTimeout(10000);
myURLConnection.setRequestProperty("Content-Type",
"application/json");
myURLConnection.setRequestProperty("Accept", "application/json");
OutputStream os = myURLConnection.getOutputStream();
os.write(input.getBytes());
os.flush();
if (myURLConnection.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ myURLConnection.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(myURLConnection.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
myURLConnection.disconnect();
} catch (MalformedURLException e) {
System.out.println("error1");
}
catch (IOException e) {
System.out.println("error2");
}
HTTP Error 401 is an authentication problem.
You need to authenticate to the server when sending the request.
This topic may help you authenticate with URLConnection :
How to handle HTTP authentication using HttpURLConnection?

connect failed: ECONNREFUSED HttpURLConnection POST internal server Android

My Native Android Application calls the web service hosted in my organization internal server which works in our network.
I am using Async task to do the HTTP POST connection using HttpURLConnection. When I do DataOutputStream wr = new DataOutputStream(conn.getOutputStream());, it is giving java.net.ConnectException: failed to connect to /10.xxx.xxx.xxx (port 90): connect failed: ECONNREFUSED (Connection refused)
try {
for (String currentUrl : urls) {
// 1. URL
URL url = new URL(currentUrl);
// 2. Open connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 3. Specify POST method
conn.setRequestMethod("POST");
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// 4. Set the headers
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
// 5. Add JSON data into POST request body
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(requestObject.toString());
wr.flush();
wr.close();
// 6. Get the response
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 7. Print result
System.out.println(response.toString());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Where I am going wrong ? Kindly suggest me

Java .getInputStream() openConnection() HTTP response code ERRORS

I am trying to do the following (in Java):
connect to some proxy server & http_url some
But I am having some errors like :
java.net.ConnectException: Connection timed out: connect...
Or errors related to HTTP response code : 302, 400, FileNotFound, file server error, etc.
In some changes I did, I even got 200 code.
(when I only use openConnection() =>( without the proxy IP address).
That is my best run trace.
I have had all class of : (Unknown Source) in the error msg, from IDE Eclipse Luna console.
Some of the error come in the form / or from : .getInputStream() method, I don't know if there is about setDoInput(), setDoOutput, the Encoding, or whatever:
Can some body help me?
Here is my code:
url = new URL(http_url);
HttpURLConnection conn;
try {
conn = (HttpURLConnection)url.openConnection(proxy);
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", USERAGENT);
conn.setUseCaches(false);
conn.setRequestProperty("Accept", "*/*");
conn.addRequestProperty("Referer", "http://www.google.com/");
conn.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.8");
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
conn.setDoInput(true);
System.out.println("response msg " + conn.getResponseMessage() + " CODE");
System.out.println("errorStream msg " + conn.getErrorStream());
System.out.println("inputStream msg " + conn.getInputStream());
String header_date = conn.getHeaderField("Date");
System.out.println(" date es: " + header_date);
String line = null;
StringBuffer tmp = new StringBuffer();
System.out.println("the code is :" + conn.getResponseCode());
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
while ((line = in.readLine()) != null) {
tmp.append(line);
}
System.out.println("value line is: " + line +"& date is: " + header_date);
Scrape(String.valueOf(tmp)); // temp.toString()
in.close();
in = null;
url = null;
conn.disconnect();
conn = null;
} else {
System.out.println("something bad happened code <>200, debug from your server");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
To solve your Proxy problem you can try using Proxy as below
Proxy proxy= new Proxy(Proxy.Type.HTTP, new InetSocketAddress(<Proxy IP Address as String>, <Proxy Port Number as Integer>));
HttpURLConnection http_conn=(HttpURLConnection)request_url.openConnection(proxy);

FileNotFoundException on HttpsURLConnection with POST and unmutable doOutput variable

I'm trying to POST some data to an https url, in my android application, in order to get a json format response.
I'm facing two problems:
is = conn.getInputStream();
throws
java.io.FileNotFoundException
I don't get if i do something wrong with HttpsURLConnection.
The second problem arose when i debug the code (used eclipse); I set a breakpoint after
conn.setDoOutput(true);
and, when inspecting conn values, I see that the variable doOutput remain set to false and type GET.
My method for https POST is the following, where POSTData is a class extending ArrayList<NameValuePair>
private static String httpsPOST(String urlString, POSTData postData, List<HttpCookie> cookies) {
String result = null;
HttpsURLConnection conn = null;
OutputStream os = null;
InputStream is = null;
try {
URL url = new URL(urlString);
conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setUseCaches (false);
conn.setDoInput(true);
conn.setDoOutput(true);
if(cookies != null)
conn.setRequestProperty("Cookie",
TextUtils.join(";", cookies));
os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(postData.getPostData());
writer.flush();
writer.close();
is = conn.getInputStream();
BufferedReader r = new BufferedReader(
new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
result = total.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (conn != null) {
conn.disconnect();
}
}
return result;
}
A little update: apparently eclipse debug lied to me, running and debugging on netbeans shows a POST connection. Error seems to be related to parameters i'm passing to the url.
FileNotFoundException means that the URL you posted to doesn't exist, or couldn't be mapped to a servlet. It is the result of an HTTP 404 status code.
Don't worry about what you see in the debugger if it doesn't agree with how the program behaves. If doOutput really wasn't enabled, you would get an exception obtaining the output stream.

Categories