HTTP POST request with JSON String in JAVA is not working - java

I have the below small code to get the json reply from service providers, what i have tried is that to post a http post request but it always throws
java.net.UnknownHostException: directory.qantasloyalty.com
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:177)
at java.net.Socket.connect(Socket.java:519)
at java.net.Socket.connect(Socket.java:469)
at sun.net.NetworkClient.doConnect(NetworkClient.java:157)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:382)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:509)
at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:278)
at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:335)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:176)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:769)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:162)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:861)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:230)
at Test.Httptestpost.sendPost(Httptestpost.java:124)
at Test.Httptestpost.main(Httptestpost.java:32)
PLease find my code below,
private void sendPost() {
System.getProperties().put("http.proxySet", "true");
System.getProperties().put("http.proxyHost", "proxyurl");
System.getProperties().put("http.proxyPort", "8080");
System.getProperties().put("http.proxyUser", "username");
System.getProperties().put("http.proxyPassword", "pwd");
System.getProperties().put("http.nonProxyHosts", "localhost|127.0.0.1");
String url = "httpsurlhere";
URL obj = null;
try {
obj = new URL(url);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpsURLConnection con = null;
try {
con = (HttpsURLConnection) obj.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//add reuqest header
try {
con.setRequestMethod("POST");
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//con.setRequestProperty("User-Agent", USER_AGENT);
//con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/json;UTF-8");
String urlParameters = "username=demouser&password=aDemoPassword";
String input = "{\"username\":\"demouser\",\"password\":\"aDemoPassword\"}";
System.out.println("input"+input);
System.out.println("url"+con.getURL());
System.out.println("req prop :"+con.getRequestProperties());
// Send post request
con.setDoOutput(true);
DataOutputStream wr;
try {
wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(input);
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());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Can someone please help me to route the cause
For security purpose I have not shared the exact proxy URL and http post webservice URl also here

please go through these sample codes:-
public static String handlePostRequest(String X, String Y)
throws IOException {
URL url = new URL(X);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Content-Length",
String.valueOf(Y.length()));
// Write data
OutputStream os = connection.getOutputStream();
os.write(Y.getBytes());
// Read response
String responseSB = "";
BufferedReader br = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = br.readLine()) != null)
responseSB += line;
// Close streams
br.close();
os.close();
return responseSB;
}

Related

JAVA rest assure get request with auth token

I am trying to create a post request with auth token but I am getting null response. Can you please help me.Can you please let me know what am I missing in the code ?
public static void main(String[] args) {
try {
String url = "https://test.abc.com/";
String token="XXXXXX-abcd-496a-ae73-7659587896";
URL object = new URL(url);
HttpURLConnection con = (HttpURLConnection) object.openConnection();
con.setDoInput(true);
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Authorization", "Bearer " + token);
//Display what the GET request returns
StringBuilder sb = new StringBuilder();
int HttpResult = con.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream(), "utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
System.out.println(con.getResponseMessage());
} else {
System.out.println(con.getResponseMessage());
}
} catch (Exception e) {
System.out.println(e);
}
}
}

Switch to POST method in java doesn't work

I can't understand how to switch to POST method in my HttpsURLConnection. On the debugger the request method is GET also after the setRequestMethod method. Can you tell me where is my mistake?
try {
URL url=new URL("https://smartmates.herokuapp.com");
HttpsURLConnection connection= (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
//I'll add some params here
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Thank you very much.
This is a piece of code that I use to POST the String mensaje and receiving rta.ToString(). I think that DoSetInput(true) is a mistake, because you want to send a POST (output) and, eventually, get a response.
`
String urlParametros = "<?xml version=\"1.0\"?>";
urlParametros = urlParametros + mensaje;
byte[] postDatos = urlParametros.getBytes(StandardCharsets.UTF_8);
try {
URL miurl = new URL(url);
con = (HttpURLConnection) miurl.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
//******…………..
con.setRequestProperty("User-Agent", "Java client");
con.setRequestProperty("Content-Type", "text/xml");
try (DataOutputStream datos = new DataOutputStream(con.getOutputStream())) {
datos.write(postDatos);
}
StringBuilder rta;
try (BufferedReader entrada = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String linea;
rta = new StringBuilder();
while ((linea = entrada.readLine()) != null) {
rta.append(linea);
rta.append(System.lineSeparator());
}
}
return rta.toString();
} finally {
con.disconnect();
}´
Hope it helps
Daniel

HttpURLConnection response is not working

In my project I have url
like:
localhost:8080/myproject/examples/12
It contains Json values..To access this field Need to put access key as Header.
Now, What I have done is that :
private String doHttpUrlConnectionAction(String desiredUrl)
throws Exception
{
URL url = null;
BufferedReader reader = null;
StringBuilder stringBuilder;
try
{
// create the HttpURLConnection
url = new URL(desiredUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// just want to do an HTTP GET here
connection.setRequestMethod("GET");
// connection.setRequestProperty("Content-Type","application/json");
connection.setRequestProperty("API-KEY", "value");
// uncomment this if you want to write output to this url
connection.setDoOutput(true);
// give it 15 seconds to respond
connection.setReadTimeout(15*1000);
connection.connect();
// read the output from the server
// reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}
catch (Exception e)
{
e.printStackTrace();
throw e;
}
finally
{
// close the reader; this can throw an exception too, so
// wrap it in another try/catch block.
if (reader != null)
{
try
{
reader.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
}
this code returns output :
Response Code : 200
<table border="0" cellpadding="4" cellspacing="0"><thead><tr><th>status</th><th>statusCode</th><th>data</th></tr></thead><tbody><tr><td statusCode="200" status="1">Array</td></tr></tbody></table>
But when I am accessing this code in httclient, I am getting value properly..
public String ReadHttpResponse(String url){
StringBuilder sb= new StringBuilder();
HttpClient client= new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
httpget.addHeader("API-KEY", "value");
try {
HttpResponse response = client.execute(httpget);
StatusLine sl = response.getStatusLine();
int sc = sl.getStatusCode();
if (sc==200)
{
HttpEntity ent = response.getEntity();
InputStream inpst = ent.getContent();
BufferedReader rd= new BufferedReader(new InputStreamReader(inpst));
String line;
while ((line=rd.readLine())!=null)
{
sb.append(line);
}
// System.out.println(sb.toString());
}
else
{
System.out.println("I didn't get the response!");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
Here,I am getting output properly..
Where is the problem in HttpUrlConnection?? What am I doing wrong here?? I have to use HttpUrlConnection.Please guys help me out..
You can make code logic like this for both request POST and GET. It helps to reduce code complexity. You can make one method for that and pass parameter to it as needed for GET and POST methods.
HttpURLConnection urlConnection = null;
try {
// http client
murl=new URL(url);
urlConnection = (HttpURLConnection) murl.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json;odata=verbose");
urlConnection.setRequestProperty("Accept", "application/json;odata=verbose");
// Checking http request method type
if (method == POST) {
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
if(!jsondata.equals("null")) {
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(jsondata);
writer.flush();
writer.close();
os.close();
}
} else if (method == GET) {
// appending params to url
urlConnection.setRequestMethod("GET");
}
resCode = urlConnection.getResponseCode();
Log.i("TAG", "response code=>" + resCode);

Want to make perl code for oauth2 work in Java "curl -H 'Authorization: Bearer:<TOKEN> https://canvas.instructure.com/api/v1";

I am getting an error that I am unauthorized.. RESPONSE CODE 401
The token I am using works in perl..
This is what I have tried till now:
public static void main(String[] args) throws Exception {
try {
String auth = returnAuth(); //getting token from a file.
//System.out.println(auth);
String url1= "https://canvas.instructure.com/api/v1";
URL url = new URL(url1+"/courses");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
//connection.setRequestProperty("Authorization", "Bearer " + auth);
connection.setRequestProperty("Authorization", "Bearer "+auth);
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response code:" + connection.getResponseCode());
System.out.println("Response message:" + connection.getResponseMessage());
// Read the response:
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
StringBuffer response = new StringBuffer();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
System.out.println(response.toString());
}
catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
try {
String auth = returnAuth(); //getting token from a file.
String url1= "https://canvas.instructure.com/api/v1/courses";
URL url = new URL(url1);
HttpsURLConnection connection =(HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Bearer "+auth);
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response code:" + connection.getResponseCode());
System.out.println("Response message:" + connection.getResponseMessage());
// Read the response:
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
}
You have it commented out but every Oauth server I've dealt with would be "Bearer <token>" - one space and no colon.
You set the parameters AFTER you called!
Change your code to first set the authentication, then open the connection.
String url1= "https://canvas.instructure.com/api/v1";
URL url = new URL(url1+"/courses");
connection.setRequestProperty("Authorization", "Bearer "+auth);
connection.setRequestMethod("GET");
//now you can open the connection...
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

How to stream a JSON object to a HttpURLConnection POST request

I can not see what is wrong with this code:
JSONObject msg; //passed in as a parameter to this method
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setDoInput(true);
httpCon.setUseCaches(false);
httpCon.setRequestProperty( "Content-Type", "application/json" );
httpCon.setRequestProperty("Accept", "application/json");
httpCon.setRequestMethod("POST");
OutputStream os = httpCon.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
msg.write(osw);
osw.flush();
osw.close();
os.close(); //probably overkill
On the server, I am getting no post content at all, a zero length string.
Try
...
httpCon.setRequestMethod("POST");
httpCon.connect(); // Note the connect() here
...
OutputStream os = httpCon.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
...
osw.write(msg.toString());
osw.flush();
osw.close();
to send data.
to retrieve data try:
BufferedReader br = new BufferedReader(new InputStreamReader( httpCon.getInputStream(),"utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
System.out.println(""+sb.toString());
public String sendHTTPData(String urlpath, JSONObject json) {
HttpURLConnection connection = null;
try {
URL url=new URL(urlpath);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream());
streamWriter.write(json.toString());
streamWriter.flush();
StringBuilder stringBuilder = new StringBuilder();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(streamReader);
String response = null;
while ((response = bufferedReader.readLine()) != null) {
stringBuilder.append(response + "\n");
}
bufferedReader.close();
Log.d("test", stringBuilder.toString());
return stringBuilder.toString();
} else {
Log.e("test", connection.getResponseMessage());
return null;
}
} catch (Exception exception){
Log.e("test", exception.toString());
return null;
} finally {
if (connection != null){
connection.disconnect();
}
}
}`
call this methopd in doitbackground in asynctask
HttpURLConnection is cumbersome to use. With DavidWebb, a tiny wrapper around HttpURLConnection, you can write it like this:
JSONObject msg; //passed in as a parameter to this method
Webb webb = Webb.create();
JSONObject result = webb.post("http://my-url/path/to/res")
.useCaches(false)
.body(msg)
.ensureSuccess()
.asJsonObject()
.getBody();
If you don't like it, there is a list of alternative libraries on the link provided.
Why should we all write the same boilerplate code every day? BTW the code above is more readable and less error-prone. HttpURLConnection has an awful interface. This has to be wrapped!
Follow this example:
public static PricesResponse getResponse(EventRequestRaw request) {
// String urlParameters = "param1=a&param2=b&param3=c";
String urlParameters = Piping.serialize(request);
HttpURLConnection conn = RestClient.getPOSTConnection(endPoint, urlParameters);
PricesResponse response = null;
try {
// POST
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
// RESPONSE
BufferedReader reader = new BufferedReader(new InputStreamReader((conn.getInputStream()), StandardCharsets.UTF_8));
String json = Buffering.getString(reader);
response = (PricesResponse) Piping.deserialize(json, PricesResponse.class);
writer.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
conn.disconnect();
System.out.println("PricesClient: " + response.toString());
return response;
}
public static HttpURLConnection getPOSTConnection(String endPoint, String urlParameters) {
return RestClient.getConnection(endPoint, "POST", urlParameters);
}
public static HttpURLConnection getConnection(String endPoint, String method, String urlParameters) {
System.out.println("ENDPOINT " + endPoint + " METHOD " + method);
HttpURLConnection conn = null;
try {
URL url = new URL(endPoint);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "text/plain");
} catch (IOException e) {
e.printStackTrace();
}
return conn;
}
this without json String post data to server
class PostLogin extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String response = null;
Uri.Builder builder= new Uri.Builder().appendQueryParameter("username","amit").appendQueryParameter("password", "amit");
String parm=builder.build().getEncodedQuery();
try
{
response = postData("your url here/",parm);
}catch (Exception e)
{
e.printStackTrace();
}
Log.d("test", "response string is:" + response);
return response;
}
}
private String postData(String path, String param)throws IOException {
StringBuffer response = null;
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
// connection.setRequestProperty("Content-Type", "application/json");
// connection.setRequestProperty("Accept", "application/json");
OutputStream out = connection.getOutputStream();
out.write(param.getBytes());
out.flush();
out.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
response = new StringBuffer();
while ((line = br.readLine()) != null) {
response.append(line);
}
br.close();
}
return response.toString();
}

Categories

Resources