I am using the below Java code to download the response from SOAP API. Soap API response contains Binary Data stream file. I am able to get the whole response with Binary data. I would need to download only Binary attachment file alone from Soap API.
Output:
enter image description here
Java code
String url = "https://services-sd02.drivecam.com/DCSubmission/EventFileStreamingService.svc";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "text/xml");
con.setRequestProperty("SOAPAction",
"http://DriveCam.com/Services/IEventFileStreamingService/GetEventFileById");
String xml = "Input Xml";
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(xml);
wr.flush();
wr.close();
String responseStatus = con.getResponseMessage();
System.out.println(responseStatus);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String responseString = response.toString();
String out = responseString;
byte[] stream = out.getBytes();
FileOutputStream out1 = new FileOutputStream("P:/Informatica/data/zd_misc/TgtFiles/Binary_File");
out1.write(stream);
out1.close();
}
}
Related
I have a web service and I want to invoke that with "application/x-www-form-urlencoded" content type. The request sometimes contains special characters such as + * - and .... The problem is that destination web service doesn't receive the request perfectly. It receives something like this: "////////////////w==" almost all characters are turned to / . What is the problem?
Here is my code:
URL url = new URL("a-web-service-url");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8");
outputStreamWriter.write("test=/-+*=!##$%^&*()_");
outputStreamWriter.flush();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder;
String line;
for (stringBuilder = new StringBuilder(); (line = bufferedReader.readLine()) != null; stringBuilder = stringBuilder.append(line)) {
;
}
bufferedReader.close();
httpURLConnection.disconnect();
String response = stringBuilder.toString().trim();
The web service receives:
test=////////////////w==
Use URLEncoder to encode the string before sending.
URLEncoder.encode(message, "UTF-8" );
In this case it will be
outputStreamWriter.write(URLEncoder.encode("test=/-+*=!##$%^&*()_", "UTF-8" ));
I would like to obtain the response from a HttpsURLConnection POST request.
If I try to do the request with PostMan, I have one message as response (es: 1520). I have to save this code, but I find the method for read just the getResponseCode() (200) or getResponseMessage() ("OK"). I should use another libraries? Because in the HttpsUrlConnection method I don't find anything useful (https://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html)
My code is:
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setSSLSocketFactory(sslContext.getSocketFactory());
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "keep-alive");
con.setRequestProperty("Content-Type", w_AECONTYP);
con.setRequestProperty("Accept-Charset", w_AEACCCHA);
con.setRequestProperty("Accept-Encoding", w_AEACCENC);
StringBuilder postFile = new StringBuilder();
byte[] postFileBytes =w_FileToSend.getBytes("UTF-8");
con.setDoOutput(true);
try {
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.write(postFileBytes);
wr.flush();
wr.close();
} catch (Exception e) {
System.out.println("Connection Failed");
e.printStackTrace();
}
int responseCode = con.getResponseCode();
// get 200 code "OK"
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
But when arrived at the WHILE loop, it doesn't enter in the cycle.
How I can do this?
The file is in JSON format, but that isn't the problem.
I need to save that 915 code!!
You could use HttpResponse and HttpPost for getting a response from server (as well as the Response Code):
HttpResponse httpResponse = httpClient.execute(new HttpPost(URL));
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
// now response is in the stringBuilder.toString()
I hope this will help you.
I'm trying to get a json object from the url:
http://www.alfanous.org/jos2?action=search&unit=aya&fuzzy=True&query=حم
However, when I run my code with that url, I got an empty json, and when I'm request the url from my browser, the josn is filled.
what is wrong with my code?
URL url = new URL("http://www.alfanous.org/jos2?action=search&unit=aya&fuzzy=True&query=حم");
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
Scanner scan = new Scanner(is);
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
And I tried also
// Create URL object
URL obj = new URL("http://www.alfanous.org/jos2?action=search&unit=aya&fuzzy=True&query=حم");
// Communicate with the URL by HTTP
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
// add request header
con.setRequestProperty("User-Agent", "Mozilla/5.0");
// Getting response data
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
The solution was to encode the url string before passing it to the URL constructor.
String urlstring = "http://www.alfanous.org/jos2?action=search&unit=aya&fuzzy=True&query=حم";
URLEncoder.encode(urlstring, "UTF-8");
URL url = new URL(urlstring);
Then continues with the previous code shown in the original post.
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
Scanner scan = new Scanner(is);
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
And the moral is.. I should encode the url before I use it!
Try to use BufferedReader like this:
URL url = new URL("http://www.alfanous.org/jos2?action=search&unit=aya&fuzzy=True&query=حم");
URLConnection conn = url.openConnection();
BufferedReader br =new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((thisLine = br.readLine()) != null) {
System.out.println(thisLine);
}
Hello I was wondering if somebody could help me with the following, I have a database that is currently populated. I used to call it using the http client and it worked fine but now I'm trying to update the code since its been deprecated to use the httpurlconnection but i have no success. I ve looked up some tutorials and tried a few thing but it doesn't seem to be working. the database is called through a php file and returns it in a json format.If i were to call the php file from my browser the response is the following: [{"id":"15","logo":"logo url","title":"title"}]
The error that I get on the console is the following:java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.InputStream.close()' on a null object reference
Which its not making much sense to me since the script pulls information
I have the following code, i left the commented section just in case i need any of it, It also includes the old way i used to call the DB Thank you!:
public void loadNews(){
InputStream is = null;
String result = "";
ArrayList<NameValuePair>();
try {
URL url = new URL("http://databasecall.php");
//HttpClient httpclient = new DefaultHttpClient();
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//urlConnection.setRequestMethod("GET");
//urlConnection.setRequestProperty("Content-length", "0");
//urlConnection.setUseCaches(false);
//urlConnection.setAllowUserInteraction(false);
//urlConnection.setConnectTimeout(15000);
//urlConnection.setReadTimeout(15000);
//urlConnection.connect();
int responseCode = urlConnection.getResponseCode();
Log.i("Tag:", Integer.toString(responseCode)); //tag 200
//HttpPost httppost = new HttpPost("http://databasecall.php");
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//HttpResponse response = httpclient.execute(httppost);
//HttpEntity entity = response.getEntity();
//is = entity.getContent();
/*}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}*/
//convert response to string
//try{
//BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.i("Tag:", result);
}
}catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
Updated API
try {
String urlParameters = "name=toni&class=one¶m3=ok";
byte[] postData = urlParameters.getBytes(Charset.forName("UTF-8"));
int postDataLength = postData.length;
String request = "http://rocks.php";
URL url = new URL(request);
HttpURLConnection cox = (HttpURLConnection) url.openConnection();
cox.setDoOutput(true);
cox.setDoInput(true);
cox.setInstanceFollowRedirects(false);
cox.setRequestMethod("POST");
cox.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
cox.setRequestProperty("charset", "utf-8");
cox.setRequestProperty("Content-Length",
Integer.toString(postDataLength));
cox.setUseCaches(false);
OutputStreamWriter writer = new OutputStreamWriter(
cox.getOutputStream());
writer.write(urlParameters);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(
cox.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
} catch (Exception e) {
result = e.toString();
Sucess = false;
e.printStackTrace();
}
I've got a webserver setup ready to receive images and I'd like to have a client in Java send the image along with two POST arguments, upon searching the web I only found ways to do this with Apache's API but I'd prefer to do this in vanilla Java.
Any help will be appreciated.
Something along the lines of...
String url = "https://asite.com";
URL obj = new URL(url);
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 = "aparam=1&anotherparam=2";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
You can add more headers, and add more to the output stream as required.