Hi All, I am struggling in rest API where i need to post an XML in body with header and get the response, can anyone post an example of how to do it? - rest

String reqURL = baseUrl + data_oauth.get(PropLoad.getTestXmlData("URL"));
Template template = new Template();
String updatedUrl = template.getUpdatedURL(reqURL);
Map<String, String> headers = Template.getRequestData(data_oauth,PropLoad.getTestXmlData("HEADER"));
headers.entrySet().toString();
String updatedAuthor = template.getAuthorizationHeader(headers, methodDesc);
headers.put("Authorization", updatedAuthor);
String xmlRequest = Template.generateStringFromResource(data_oauth,"xmlbody");
Response response = webCredentials_rest.postCallWithHeaderAndBodyParamForXml(headers, xmlRequest, updatedUrl);
// am getting Unmarshalled as in response, can any help me on posting an POST request with XML body in it

You can send it like this:
URL url = new URL(urlString);
URLConnection connenction = url.openConnection();
OutputStream output = connenction.getOutputStream();
InputStream input = new FileInputStream(xmlFile);
byte[] buffer = new byte[4096];
int len;
while ((len = input .read(buffer)) >= 0) {
out.write(buffer, 0, len);
}
input .close();
output.close();
And read the response like this:
StringBuilder stringBuilder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connenction.getInputStream()));
String readLine = reader.readLine();
while (readLine != null) {
stringBuilder.append(readLine);
readLine = br.readLine();
}

Related

Getting connection reset error while getting big response from soap API

Can anyone tell me what I am missing here, same code is working when response size is less. Here in the response getting xls file in encrpypted format. When file size is big, getting connection reset error.
Code to make a webservice HTTP request
String responseString = "";
String outputString = "";
String wsURL = System.getenv("ORACLE_ENDPOINT");
URL url = new URL(wsURL);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
String xmlInput = requestPayloader(requestId_1, GroupId, RequestId_2, interfaceType);
byte[] buffer = new byte[xmlInput.length()];
buffer = xmlInput.getBytes();
bout.write(buffer);
byte[] b = bout.toByteArray();
String SOAPAction = "url";
// Set the appropriate HTTP parameters.
// refer username and password from Key Valut
KeyVault keyVault = new KeyVault();
String userName = keyVault.GetSecretFromVault(System.getenv("ORACLE_ENDPOINT_USERNAME"));
String password = keyVault.GetSecretFromVault(System.getenv("ORACLE_ENDPOINT_PASSWORD"));
// String auth = System.getenv("ORACLE_ENDPOINT_USERNAME") + ":" +
// System.getenv("ORACLE_ENDPOINT_PASSWORD");
String auth = userName + ":" + password;
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.UTF_8));
String authHeaderValue = "Basic " + new String(encodedAuth);
httpConn.setRequestProperty("Content-Type", "application/soap+xml");
httpConn.setRequestProperty("SOAPAction", SOAPAction);
httpConn.setRequestProperty("Authorization", authHeaderValue);
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setReadTimeout(0);
OutputStream out = httpConn.getOutputStream();
out.write(b);
//out.close();
InputStreamReader isr = new InputStreamReader(httpConn.getInputStream());
BufferedReader in = new BufferedReader(isr);
while ((responseString = in.readLine()) != null) {
outputString = outputString + responseString;
}
return outputString;

Get body of Bad Request httpURLConnection.getInputStream()

I've been working on a portlet that calls Rest API. When the API is called and the requested data doesn't exist, it returns an appropriate error message in JSON format (with Bad request http code - 400), and if the id exists, it returns the requested data in json (with code 200).
How can I get the body of response (that contains error description) because invoking httpConn.getInputStream() method throws exception in case the response is bad request error.
Code:
HttpURLConnection httpConn = null;
URL url = new URL("http://192.168.1.20/personinfo.html?id=30");
URLConnection connection = url.openConnection();
httpConn = (HttpURLConnection) connection;
httpConn.setRequestProperty("Accept", "application/json");
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("charset", "utf-8");
BufferedReader br = null;
if (!(httpConn.getResponseCode() == 400)) {
br = new BufferedReader(new InputStreamReader((httpConn.getInputStream())));
String output;
StringBuilder builder = new StringBuilder();
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null)
builder.append(output);
return builder.toString();
}else
here should catch the error message. :)
In case of non-successful response codes, you have to read the body with HttpURLConnection.getErrorStream().
you can get body of Bad Request in HttpURLConnection using this code :
InputStream errorstream = connection.getErrorStream();
String response = "";
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(errorstream));
while ((line = br.readLine()) != null) {
response += line;
}
Log.d("body of Bad Request HttpURLConnection", "Response: " + response);
Use Apache Httpclient:
String url = "http://192.168.1.6:7003/life/lifews/getFirstInstallment.html?rootPolicyNo=1392/2126/2/106/9995/1904&token=1984";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add request header
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);
System.out.println(result);

Paypal Rest services - Response: Internal Service Error

This is my code. I am not using Maven or curl.
String encoding = Base64.encodeBase64String((clientId + ":" + clientSecret).getBytes());
encoding = encoding.replaceAll("\n", "");
URL url1 = new URL("https://api.sandbox.paypal.com/v1/oauth2/token");
HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("grant_type", "client_credentials");
conn.setRequestProperty("Authorization", "Basic " + encoding);
System.out.println(conn.getResponseCode());
if (conn.getResponseCode() == 500) {
InputStream error = conn.getErrorStream();
BufferedReader er = new BufferedReader(new InputStreamReader(error));
String erLine;
while ((erLine = er.readLine()) != null) {
System.out.println(erLine);
}
}
InputStream content = conn.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
conn.disconnect();
OUTPUT:
500
{"name":"INTERNAL_SERVICE_ERROR","information_link":"https://api.sandbox.paypal.com/docs/api/#INTERNAL_SERVICE_ERROR","debug_id":"023ff49775e72"}
PROBLEM:
Well, when I do this call using curl, it gives me an appropriate response. Are the services not equipped to do communication is this way ?
Can you print your Authorization header and inspect whether it's correctly populated? We are currently returning a HTTP500 if your Authorization header is empty (which we'll change to return a more appropriate error obviously).

Blackberry HttpConnection and query string

I've been having some trouble connecting to a uri when I append a query string... I always get back 400 http code... however when I try the browser, same url, everything goes smooth...
This is what I have:
String query = "q=hello";
byte[] queryBytes = query.getBytes();
Somewhere in my code I open an HttpConnection using the queryBytes like this:
String uri = "https://www.google.co.ve/search" + "?" + new String(queryBytes);
HttpConnection request = (HttpConnection) Connector.open(uri);
request.getResponseCode();
If I don't use bytes for my connection everyting works fine:
String uri = "https://www.google.co.ve/search?q=hello";
Thanks in advance
When i try this, iam getting http code 200.
try {
String httpURL = "https://www.google.co.ve/search?q=hello";
HttpConnection httpConn;
httpConn = (HttpConnection) Connector.open(httpURL);
httpConn.setRequestMethod(HttpConnection.GET);
DataOutputStream _outStream = new DataOutputStream(httpConn.openDataOutputStream());
byte[] request_body = httpURL.getBytes();
for (int i = 0; i < request_body.length; i++) {
_outStream.writeByte(request_body[i]);
}
DataInputStream _inputStream = new DataInputStream(
httpConn.openInputStream());
StringBuffer _responseMessage = new StringBuffer();
int ch;
while ((ch = _inputStream.read()) != -1) {
_responseMessage.append((char) ch);
}
String res = (_responseMessage.toString());
String responce = res.trim();
httpConn.close();
Dialog.alert(responce);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Sending multiple parameters to POST method in .net:

I'm struggling to use POST method for RESTful services. My requirement is some parameters I need to append (not in the URL) and 2 parameters I need to read from file. The service is written in Java.
string url= "http://srfmdpimd2:18109/1010-SF-TNTIN/Configurator/rest/importConfiguration/"
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
FileStream file = new FileStream(#"TestSCDS.properties", FileMode.Open);
Byte[] bytes = new Byte[file.Length];
file.Read(bytes, 0, bytes.Length);
string strresponse = Encoding.UTF8.GetString(bytes);
request.Method = "POST";
request.ContentType = "multipart/form-data;";
request.ContentLength = file.Length;
request.Headers.Add("hhrr", "H010");
request.Headers.Add("env", "TEST");
request.Headers.Add("buildLabel", "TNTAL_05.05.0500_C54");
Stream Postdata = request.GetRequestStream();
Postdata.Write(bytes, 0, bytes.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();`
request.Headers.Add() is adding parameters to URL? If not, how can I send multiple parameters to POST method in restful services?
Also, how to read parameters from file and make use in POST method?
It needs a little leg work, encode a dictionary and put it in the body. Below is a quick sample:
private string Send(string url)
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
string postData = EncodeDictionary(args, false);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] postDataBytes = encoding.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postDataBytes.Length;
using(Stream requestStream = request.GetRequestStream())
{
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
}
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
return reader.ReadToEnd();
}
}
private string EncodeDictionary(Dictionary<string, string> dict,
bool questionMark)
{
StringBuilder sb = new StringBuilder();
if (questionMark)
{
sb.Append("?");
}
foreach (KeyValuePair<string, string> kvp in dict)
{
sb.Append(HttpUtility.UrlEncode(kvp.Key));
sb.Append("=");
sb.Append(HttpUtility.UrlEncode(kvp.Value));
sb.Append("&");
}
sb.Remove(sb.Length - 1, 1); // Remove trailing &
return sb.ToString();
}
I don't know what your complete requirements are, but my strong suggestion is to "start simple".
Do not use "Content-type: multipart/form-data" unless you're sure you need it. Instead, start out with "application/x-www-form-urlencoded" (an old favorite) or "application/json" (even better).
Here is a nice little step-by-step example. You can find literally 100's more with a simple Google search:
http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client