Connection to distant server using HttpURLConnection - java

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?

Related

java.lang.RuntimeException: Failed : HTTP error code : 400

I am trying to post a json data to a URL, I have no idea where my code went wrong, I am getting Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 400 It would be of great help if anyone could help me outwith this issue.
Using postman I can perform the post operation, but through code it always throws 400.
I tried searching many posts but none of them work, I am stuck with this error.
try {
URL url = new URL("https://XXX/approvals");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("APIKEY", "abc");
conn.setRequestProperty("Authorization","Bearer abc");
String input = "{\"users\":\"100\"}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
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();
}
Error:
Post parameters : {"users":"100"}
Response Code : 400
java.lang.RuntimeException: Failed : HTTP error code : 400Cannot Estabilish Connection Failed : HTTP error code : 400
at com.Test.main(Test.java:46)

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();
}

Getting Network is unreachable on IPV6 Network

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.

Issue while fetching Users data from Azure AD

I am trying to fetch users available in Azure AD. While fetching, http 401 Authentication Error Encountered and IOException caught on console. Following is the method through which I am trying to fetch data-
public String getUsers(String accessToken) {
URL url;
String line = "";
try {
System.out.println("\n\n***************Available Users ************\n");
url = new URL("https://graph.windows.net/" + tenant_id
+ "/users");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// Set the appropriate header fields in the request header.
con.setRequestMethod("GET");
con.setRequestProperty("api-version", "1.6");
con.setRequestProperty("Authorization", "Bearer " + accessToken);
con.setRequestProperty("Accept", "application/json;odata=minimalmetadata");
int responseCode = con.getResponseCode();
System.out.println("Responsecode : " + responseCode);
line=HttpClientHelper.getResponseStringFromConn(con,true);
System.out.println("Line data"+line);
/*if (responseCode == 200) {
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
} else {
reader = new BufferedReader(new InputStreamReader(con.getErrorStream()));
}
StringBuffer stringBuffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
stringBuffer.append(line);
}*/
System.out.println(line);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return line;
}
As I known, you can refer to Error Handling in OAuth 2.0 to check your issue.
Meanwhile, as #GauravMantri said, you also need to check the permission of Microsoft Graph for application in AAD, please see the figures below.
Fig 1. Checking the permission of application and adding applications
Fig 2. Click Add application and add Microsoft Graph

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

Categories