Getting connection reset error while getting big response from soap API - httpconnection

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;

Related

POST request using form-data in body with core java, getting bad request

I have written an core java code to post call with form-data(always pdf) along with Auth but i am always getting bad request.enter image description here
public class POSTAPIClientSucessFile2 {
public static void main(String[] args) throws IOException {
try {
String boundary = "";
final String LINE_FEED = "\r\n";
HttpURLConnection httpConn;
OutputStream outputStream;
PrintWriter writer;
String authData = "Bearer 3AAABLblqZhAmXYU1afunO0RBkBBOxDcE0elkSXa6WmNorjjNNGoWjQF5f_mnl21GVK4bOGjsIzqNNB1ZLLLZol--21hmnI1w";
// creates a unique boundary based on time stamp
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL("https://api.na3.echosign.com/api/rest/v6/transientDocuments");
System.out.println("URL : " + url.toString());
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
httpConn.addRequestProperty("Authorization", authData);
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);
String fileName = "C:/delete/test.pdf";
//String fieldName = "File";
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"File\"; filename=\"/C:/delete/test.pdf\"").append(LINE_FEED);
writer.append("Content-Type: application/pdf").append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
int responseCode = ((HttpURLConnection) httpConn).getResponseCode();
System.out.println("responseCode --> "+responseCode);
System.out.println("response msg--> "+((HttpURLConnection) httpConn).getResponseMessage());
System.out.println("response --> "+((HttpURLConnection) httpConn).toString());
FileInputStream inputStream = new FileInputStream(fileName);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
always getting bad request even by changing the content-type
enter image description here

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?

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();
}

How to add new header to jersey client to upload multipart file

Please find below jersey client code to upload multipart file:
String url = "http://localhost:7070"
Client client = Client.create();
WebResource webresource = client.resource(url);
File file = new File("C://Data//image1.jpg");
File thumbnail = new File("C://Data/image2.jpg");
InputStream isthumbnail = new FileInputStream(thumbnail);
InputStream isfile = new FileInputStream(file);
FormDataMultiPart multiPart = new FormDataMultiPart();
FormDataBodyPart bodyPart1 = new FormDataBodyPart(FormDataContentDisposition.name("Thumbnail").fileName("thumbnail").build(), isthumbnail, MediaType.APPLICATION_OCTET_STREAM_TYPE);
FormDataBodyPart bodyPart2 = new FormDataBodyPart(FormDataContentDisposition.name("File").fileName("file").build(), isfile, MediaType.APPLICATION_OCTET_STREAM_TYPE);
multiPart.bodyPart(bodyPart);
multiPart.bodyPart(bodyPart1);
//New Headers
String fileContentLength = "form-data; contentLength=\""+Long.toString(file.length())+ "\"";
String thumbnailContentLength = "form-data; contentLength=\""+Long.toString(file.length())+ "\"";
final ClientResponse clientResp = webresource.type(MediaType.MULTIPART_FORM_DATA_TYPE).accept(MediaType.APPLICATION_XML).post(ClientResponse.class, multiPart);
System.out.println("File Upload Success with Response"+clientResp.getStatus());
I need to add the String fileContentLength and thumbnailContentLength as header
Content-Length.
How do i add the headers as part of multipart and post the request?Any help would be appreciated
Use a FormDataContentDisposition as an argument to FormDataBodyPart(FormDataContentDisposition formDataContentDisposition, Object entity, MediaType mediaType).
final FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
final String value = "Hello World";
final FormDataContentDisposition dispo = FormDataContentDisposition
.name("file")
.fileName("test.txt")
.size(value.getBytes().length)
.build();
final FormDataBodyPart bodyPart = new FormDataBodyPart(dispo, value);
formDataMultiPart.bodyPart(bodyPart);

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).