Hello I'm wondering how could I make a https request for soap API.
In Android app, I had searched a lot but there isn't clear tutorial explaining how to do that.
Any suggestion or help please?
Thanks
import java.io.*;
import java.net.*;
import javax.net.ssl.*;
public class HttpsClient {
public static void main(String[] args) throws Exception {
String httpsURL = "https://postman-echo.com/post";
URL myUrl = new URL(httpsURL);
HttpURLConnection conn = (HttpsURLConnection) myUrl.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.append("<xml><body>your SAOP request here</body></xml>");
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
System.out.println("Response code is : "+conn.getResponseCode());
System.out.print("Response text is :");
while ((inputLine = br.readLine()) != null) {
System.out.println(inputLine);
}
out.flush();
out.close();
br.close();
}
}
SOAP request is also an http POST with an xml in the request body. You need to change the url to the web service endpoint url and replace the sample string with your SOAP request.
Related
I am trying to do a simple HTTP Get and POST request in java to my Eclipse Kura gateway but i dont know how to authenticate using username and password. I tried using the url syntax http://user:pw#ipaddress:port/ but i still get HTTP error code 401.
import java.io.*;
import java.net.*;
public class HTTP {
public static String getHTML() throws Exception {
StringBuilder result = new StringBuilder();
String urlToRead = "http://user:pw#ipaddress:port";
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
public static void main(String[] args) throws Exception {
System.out.println(getHTML());
}
}
I believe that you are not providing the credentials in the desired way. This very similar question already has an accepted answer, in which James Van Huis suggests using java.net.Authenticator for setting authentication data prior to opening any connections.
I followed a lot of tutorials to make progress with this project. Now I am following a tutorial to create a Google cloud messaging server using JSON and Jackson library.
I somehow got the right Jackson library of all the libraries on the internet. But an error appeared which is the title of this question.
This is that code:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.codehaus.jackson.map.ObjectMapper;
public class POST2GCM {
public static void post(String apiKey, Content content){
try{
//1. url
URL url = new URL("https://android.googleapis.com/gcm/send");
//2. open connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//3. specify POST method
conn.setRequestMethod("POST");
//4.set the headers
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key="+apiKey);
conn.setDoOutput(true);
//5. add json data into POST request body
//5.1 use jackson object mapper to convert contnet object into JSON
ObjectMapper mapper = new ObjectMapper();
//5.2 get connection stream
DataOutputStream wr = DataOutputStream(conn.getOutputStream());
//5.3 copy content "JSON" into
mapper.writeValue(wr, content);
//5.4 send the request
wr.flush();
//5.5
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();
}
}
}
I don't know how to fix this one, I've looked for answers but there isn't any answer.
your are missing new keyword
//5.2 get connection stream
DataOutputStream wr = DataOutputStream(conn.getOutputStream());
replace with
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
Overall I'm trying to write a script that captures the servers' response to an HTTP POST using java.
Unfortunately, I'm stuck at encoding the URL portion of it. While I followed several online example on encoding a URL, I still get MalformedURLException...
Any idea what might go wrong in the encoding process?
The error:
$ java client_post
Sending Http POST request
Exception in thread "Main Thread" java.net.MalformedURLException: no
protocol: http%3A%2F%2Fyahoo.com
at java.net.URL.<init>(URL.java:567)
at java.net.URL.<init>(URL.java:465)
at java.net.URL.<init>(URL.java:414)
at client_post.sendPost(client_post.java:30)
at client_post.main(client_post.java:23)
The code:
//package client_post;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class client_post {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
client_post http = new client_post();
System.out.println("\nSending Http POST request");
http.sendPost();
}
// HTTP POST request
private void sendPost() throws Exception {
//String url =<host:port/create/service>
String url = "http://yahoo.com";
String EncoderUrl = URLEncoder.encode(url, "UTF-8");
URL obj = new URL(EncoderUrl);
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 = "<string base64>";
// 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());
System.out.println(response.toString());
}
}
When you are encoding url your url becomes like below
http%3A%2F%2Fyahoo.com
Dont encode untill you have something special in it.
Your programm is also throwing class cast exception
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
Above should be like below
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
Below is working programm.
package com.ds.portlet.library;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class client_post {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
client_post http = new client_post();
System.out.println("\nSending Http POST request");
http.sendPost();
}
// HTTP POST request
private void sendPost() throws Exception {
//String url =<host:port/create/service>
String url = "http://yahoo.com";
// String EncoderUrl = URLEncoder.encode(url, "UTF-8");
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) 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 = "<string base64>";
// 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());
System.out.println(response.toString());
}
}
It looks like you're trying to encode the entire URL, including the :// and similar characters. The purpose of URL encoding is to hide those characters in a path or query part, and they shouldn't be encoded in the main URL. Use URLEncoder only for parameters or application/x-www-form-urlencoded contents.
I tried to understand how to send REST request to server. If I have to implement this as a request in java using httpconnections or any other connections, how would I do that?
POST /resource/1
Host: myownHost
DATE: date
Content-Type: some standard type
How should this be structured in a standard way?
URL url= new URL("http://myownHost/resource/1");
HttpsURLConnection connect= (HttpsURLConnection) url.openConnection();
connect.setRequestMethod("POST");
connect.setRequestProperty("Host", "myOwnHost");
connect.setRequestProperty("Date","03:14:15 03:14:15 GMT");
connect.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
There are many options, Apache HTTP client (http://hc.apache.org/httpcomponents-client-4.4.x/index.html) is one of them (and makes things very easy)
Creating REST requests can be as easy as this (using JSON in this case):
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(
"http://localhost:8080/RESTfulExample/json/product/get");
getRequest.addHeader("accept", "application/json");
HttpResponse response = httpClient.execute(getRequest);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
Update: Sorry the link to the documentation was updated.Posted the new one.
you should use json here
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class NetClientPost {
// http://localhost:8080/RESTfulExample/json/product/post
public static void main(String[] args) {
try {
URL url = new URL("http://myownHost/resource/1");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input = "{\"DATE\":\"03:14:15 03:14:15 GMT\",\"host\":\"myownhost\"}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
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();
}
}
}
more over it browse link
There are several ways to call a RESTful service with Java but it's not required to use raw level APIs ;-)
It exists some RESTful frameworks like Restlet or JAX-RS. They address both client and server side and aim to hide the technical plumbing of such calls. Here is a sample of code describing how to do your processing with Restlet and a JSON parser:
JSONObject jsonObj = new JSONObject();
jsonObj.put("host", "...");
ClientResource cr = new Client("http://myownHost/resource/1");
cr.post(new JsonRepresentation(jsonObject);
// In the case of form
// Form form = new Form ();
// form.set("host", "...");
// cr.post(form);
You can notice that in the previous snippet, headers Content-type, Date are automatically set for you based on what you sent (form, JSON, ...)
Otherwise a small remark, to add an element you should use a method POST on the element list resource (http://myownHost/resources/) or a method PUT if you have the unique identifier you want to use to identify it (http://myownHost/resources/1). This link could be useful to you: https://templth.wordpress.com/2014/12/15/designing-a-web-api/.
Hope it helps you,
Thierry
i am trying to make an HTTP POST request to Hackerrank API but the code is not compiling and giving the error Syntax error or token "1", < expected. One of the POST parameters is 'testcase' which needs to be a string but this is where eclipse gives an error. If i don't put " " around the 1 it works fine but now the Hackerrank API gives response code : 400 because testcase needs to be string. I can't figure out as to how to resolve this problem. Can someone please guide me.
Thanks in advance. This is the code:
package com.us.ABC;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLConnectionExample {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
HttpURLConnectionExample http = new HttpURLConnectionExample();
System.out.println("\nTesting 2 - Send Http POST request");
http.sendPost();
}
// HTTP POST request
private void sendPost() throws Exception {
String url = "http://api.hackerrank.com/checker/submission.json";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "source=print 1&lang=5&testcases=["1"]&api_key=hackerrank|282807-132|8d62bbbdf90d6a790747561f031a017b7f6cbbeb";
// 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());
}
}
You need to escape the double quotes in the string literal:
String urlParameters = "source=print 1&lang=5&testcases=[\"1\"]&api_key=hackerrank|282807-132|8d62bbbdf90d6a790747561f031a017b7f6cbbeb";