Web service Client application - java

There is a .Net web service and I have to send XML data from my local applications. My local application are running on Java & Sql.
Web service is accepting xml type. would you please help me how should I do? is there an example for this case?

I am giving you 2 examples from your java application, you post an file to service.
Apache HttpClient :
String url = "https://yoururl.com";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("xml", xmlString));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +
response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
Here's an example how to do it with java.net.URLConnection:
String url = "http://example.com";
String charset = "UTF-8";
String param1 = URLEncoder.encode("param1", charset);
String param2 = URLEncoder.encode("param2", charset);
String query = String.format("param1=%s&param2=%s", param1, param2);
URLConnection urlConnection = new URL(url).openConnection();
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true); // Triggers POST.
urlConnection.setRequestProperty("accept-charset", charset);
urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
OutputStreamWriter writer = null;
try {
writer = new OutputStreamWriter(urlConnection.getOutputStream(), charset);
writer.write(query); // Write POST query string (if any needed).
} finally {
if (writer != null) try { writer.close(); } catch (IOException logOrIgnore) {}
}
InputStream result = urlConnection.getInputStream();
// Now do your thing with the result.
Thanks
Shiva Kumar SS

Related

HTTP POST request in JAVA with payload as a json file

Below is what i tried to send a HTTP POST request which send the json file as payload. The Error I always get is
java.io.FileNotFoundException: test.json (The system cannot find the file specified)
Although the test.json file is in the same folder.
private void sendPost() throws Exception {`
String url = "url";
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
String postData = AutomaticOnboarding.readFile("test.json");
urlParameters.add(new BasicNameValuePair("data", postData));
StringEntity se = new StringEntity(postData);
post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
post.setEntity(se);
HttpResponse response = httpClient.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
int responseCode = response.getStatusLine().getStatusCode();
System.out.println("Response Code : " +responseCode);
if(responseCode == 200){
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
}
}
Here follows the readFile method:
public static String readFile(String filename) {
String result = "";
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
result = sb.toString();
} catch(Exception e) {
e.printStackTrace();
}
return result;
}
Use the class loader to get resources inside the jar
getClass().getClassLoader().getResourceAsStream(filename)

Send GET request with token using Java HttpUrlConnection

I have to work with RESTful web service which uses token-based authentication from Java application. I can successfully get token by this way:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public void getHttpCon() throws Exception{
String POST_PARAMS = "grant_type=password&username=someusrname&password=somepswd&scope=profile";
URL obj = new URL("http://someIP/oauth/token");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json;odata=verbose");
con.setRequestProperty("Authorization",
"Basic Base64_encoded_clientId:clientSecret");
con.setRequestProperty("Accept",
"application/x-www-form-urlencoded");
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
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());
} else {
System.out.println("POST request not worked");
}
}
But I cannot find a way to properly send this token in the get request. What I'm trying:
public StringBuffer getSmth(String urlGet, StringBuffer token) throws IOException{
StringBuffer response = null;
URL obj = new URL(urlGet);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
String authString = "Bearer " + Base64.getEncoder().withoutPadding().encodeToString(token.toString().getBytes("utf-8"));
con.setRequestProperty("Authorization", authString);
int responseCode = con.getResponseCode();
System.out.println("GET Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} else {
System.out.println("GET request not worked");
}
return response;
}
doesn't work. Any help to solve this problem will be highly appreciated.
Solved. Server returns some extra strings besides token itself. All I had to do is to extract pure token from the received answer and paste it without any encoding: String authString = "Bearer " + pure_token;
You should add the token to request url:
String param = "?Authorization=" + token;
URL obj = new URL(urlGet + param);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
conn.setRequestMethod("GET");
As an alternative, use restTemplate to send a get request:
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + token);
HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<String> response = restTemplate.exchange(urlGet, HttpMethod.GET, request, String.class);

openTSDB REST API is not storing data

I am trying to write to an openTSDB database so I can analyse my data using Bosun.
If I manually add data through the Bosun interface it works fine, however if i do a POST request to <docker-ip>/api/put (where <docker-ip> is configured correctly) the data does not show up in Bosun.
If I send the data points as a a JSON from my Java application nothing shows up at all in Bosun, but if I send the request using the chrome app 'Postman' then the metric shows up, but the data I sent with the request does not.
This is the data I'm sending:
try {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost("http://192.168.59.103:8070/api/put?summary");
StringEntity params = new StringEntity("{\"metric\":\"tester.example\",\"timestamp\":\"" + System.currentTimeMillis() + "\", \"value\": \"22\", \"tags\": { \"host\": \"chrisedwards\", \"dc\": \"lga\" }}");
request.setEntity(params);
request.setHeader("Content-Type", "application/json; charset=UTF-8");
HttpResponse response = httpClient.execute(request);
System.out.println(response);
// handle response here...
} catch (Exception ex) {
ex.printStackTrace();
} finally {
// httpClient.close();
}
which returns a 200 response code. I send the same request using Postmaster to the same address as in the java application however, the postmaster request shows the metric name in Bosun but no data, and the Java request doesn't even show the metric name.
Try this, it served my purpose:
try {
String url = "http://192.168.59.103:8070/api/put";
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 = "{\"metric\":\"tester.example\",\"timestamp\":\"" + System.currentTimeMillis() + "\", \"value\": \"22\", \"tags\": { \"host\": \"chrisedwards\", \"dc\": \"lga\" }}";
// 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());
}
catch(Exception e) {
e.printStackTrace();
}

Send Xml string through POST method in java

I want to pass an xml string through POST method to an URL.
I tried below snippet but it doesn't return anything
disableCertificateValidation();
String url = "https://..url"; //https
Properties sysProps = System.getProperties();
sysProps.put("proxySet", "true");
sysProps.put("proxyHost", "1.2.3.4");
sysProps.put("proxyPort", "80");
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication("userid",
"password".toCharArray()));
}
};
Authenticator.setDefault(authenticator);
String xml = ---xml string;
URL urll;
HttpURLConnection connection = null;
try {
// Create connection
urll = new URL(url);
connection = (HttpURLConnection) urll.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", ""
+ Integer.toString(xml.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
// Send request
DataOutputStream wr = new DataOutputStream(connection
.getOutputStream());
wr.writeBytes(xml);
wr.flush();
wr.close();
// Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
System.out.println("response.toString();"+response.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
But when I try to post it through jsp I get the proper response from the url.
<script type="text/javascript">
function set(){
document.getElementById("eXml").value=---xml string
document.getElementById("textt").value=document.getElementById("eXml").value;
alert(document.getElementById("eXml").value);
document.getElementById("myForm").action="https---" //https url;
document.getElementById("myForm").submit();
}
</script>
<body>
<form method="POST" id="myForm">
<input type="submit" name="send" onclick="set()">
<input type="text" id="textt" value='test'>
<input type="hidden" name="eXml" id="eXml">
Send it as parameter: Using Apache HttpClient
String url = "https://yoururl.com";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("xml", xmlString));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +
response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
if you want to send XML as text/xml with HTTP POST you should use OutputStreamWriter:
try(OutputStreamWriter osw = new OutputStreamWriter(cnn.getOutputStream)) {
osw.write(xmlData);
osw.flush();
}

HTTP/1.1 400 Bad Request Apache

I'm attempting to login to twitter using the following code I've written. The issue is on each execution i receive a 400 Bad Request back as the response. I have tried numerous attempts to get this to work to no avail.
public void login(String url) throws ClientProtocolException, IOException{
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("User-Agent", USER_AGENT);
HttpResponse response = client.execute(request);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
// set cookies
setCookies(response.getFirstHeader("Set-Cookie") == null ? "" : response.getFirstHeader("Set-Cookie").toString());
Document doc = Jsoup.parse(result.toString());
System.out.println(doc);
// Get input elements
Elements loginform = doc.select("div.clearfix input[type=hidden][name=authenticity_token]");
String auth_token = loginform.attr("value");
System.out.println("Login: "+auth_token);
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
paramList.add(new BasicNameValuePair("authenticity_token", auth_token));
paramList.add(new BasicNameValuePair("session[username_or_email]", "twitter_username"));
paramList.add(new BasicNameValuePair("session[password]", "twitter_password"));
System.out.println(paramList);
HttpPost post = new HttpPost(url);
// add header
post.setHeader("Host", "twitter.com");
post.setHeader("User-Agent", USER_AGENT);
post.setHeader("Accept", "text/html,application/xhtml;q=0.9,*/*;q=0.8");
post.setHeader("Accept-Language", "en-US,en;q=0.5");
post.setHeader("Keep-Alive", "115");
post.setHeader("Cookie", getCookies());
post.setHeader("Connection", "keep-alive");
post.setHeader("Referer", "https://twitter.com/");
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
post.setEntity(new UrlEncodedFormEntity(paramList));
// Execute POST data
HttpResponse res = client.execute(post);
int responseCode = res.getStatusLine().getStatusCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + paramList);
System.out.println("Response Code : " + responseCode);
System.out.println("Headers: "+res.getAllHeaders().toString());
System.out.println("Response: "+res.getStatusLine());
BufferedReader rd1 = new BufferedReader(
new InputStreamReader(res.getEntity().getContent()));
StringBuffer resul = new StringBuffer();
String line1 = "";
while ((line1 = rd1.readLine()) != null) {
resul.append(line1);
}
Document doc2 = Jsoup.parse(res.toString());
System.out.println(doc2);
}
public static void main(String[] args) throws ClientProtocolException, IOException{
Browser b = new Browser();
b.login("https://twitter.com/login");
}
I believe that everything that needs to be POST'd is being, such as the username, password, as well as the authenticity token.
Turns out i was sending the wrong session information in my POST request! If anyone else has a similar issue i recommend using Chrome Developer tools to inspect the headers being sent/received.

Categories

Resources