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
Related
I'm using the code below to create a http request to my amazon AWS api gateway with an object (mp3Base64) as its content. However, it needs to have the authorization token attached. Can anyone explain how this is done and show an example? Any help is gratefully received. Thanks.
public String executePost(String targetURL, Mp3Base64 mp3Base64) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String mp3Base64Json = mapper.writeValueAsString(mp3Base64);
URL obj = new URL(targetURL);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
connection = (HttpURLConnection) obj.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length",
Integer.toString(mp3Base64Json.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes("base64=" + mp3Base64Json);
wr.flush();
wr.close();
//Get Response
int responseCode = connection.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + targetURL);
System.out.println("Post parameters : base64 =" + mp3Base64Json);
System.out.println("Response Code : " + responseCode);
InputStream is = connection.getInputStream();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
return response.toString();
}
I'm trying to connect to GDAX using their REST API.
I first want to do something very simple, i.e. getting historic rates.
I tried this:
private static final String GDAX_URL = "https://api.gdax.com";
public String getCandles(final String productId, final int granularity) {
HttpsURLConnection connection = null;
String path = "/products/" + productId + "/candles";
try {
//Create connection
URL url = new URL(GDAX_URL);
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("granularity", String.valueOf(granularity));
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(path);
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuffer response = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
return null;
}
But I get a 400 code in return "Bad Request – Invalid request format".
My problem is with the passing of the path "/products//candles" and the parameters (e.g. granularity).
I don't understand what should go in the request properties and in the message itself, and in what form.
I managed to make it work like this:
URL url = new URL(GDAX_URL + path + "?granularity="+granularity);
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
Not sure how to use the DataOutputStream, so I just removed it. At least it works.
I am simply making a GET request to a Rest API using HttpURLConnection.
I need to add some custom headers but I am getting null while trying to retrieve their values.
Code:
URL url;
try {
url = new URL("http://www.example.com/rest/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Set Headers
conn.setRequestProperty("CustomHeader", "someValue");
conn.setRequestProperty("accept", "application/json");
// Output is null here <--------
System.out.println(conn.getHeaderField("CustomHeader"));
// Request not successful
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Request Failed. HTTP Error Code: " + conn.getResponseCode());
}
// Read response
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer jsonString = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
conn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
What am I missing?
It is a good idea to send
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("CustomHeader", token);
instead of
// Set Headers
conn.setRequestProperty("CustomHeader", "someValue");
conn.setRequestProperty("accept", "application/json");
Both the type value and header should be changed.
it works in my case.
The conn.getHeaderField("CustomHeader") returns the response header not the request one.
To return the request header use: conn.getRequestProperty("CustomHeader")
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?
I have a code that handle the post and get request . but it should response when the post request come . I dont want to use servlet because it need the tomcat or jetty and its become more complex .
how I should know post request recived ?
private void sendPost() throws Exception {
String url = "https://selfsolve.apple.com/wcResults.do";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
public static void main(String[] args) throws Exception {
while (true) {
HttpURLConnectionExample http = new HttpURLConnectionExample();
System.out.println("Testing 1 - Send Http GET request");
http.sendGet();
System.out.println("\nTesting 2 - Send Http POST request");
http.sendPost();
}
}