I have been trying to implement a video upload facebook feature for my mobile app for a while now but never really succeeded with rest. I learnt yesterday that the graph alternative was available.
After getting a few errors to do with access key mainly i have gotten to the point where output stream succesfully writes the movie file and the input stream just receives an empty json array once i have written the 3gp file.
Anyone any idea why I would get an empty json array and no video gets published when i get all my code to run, i get 200 response code and the server sends me a non error response?
Any help greatly appreciated.
Here is the class that gets the blank json array (send method). I have appended the token to the url and in the table to be sure. I am sorry if the code is untidy buts it just been a day of trial and error.
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.io.http.HttpProtocolConstants;
public class HttpMultipartRequest2
{
static final String BOUNDARY = "----------V2ymHFg03ehbqgZCaKO6jy";
byte[] postBytes = null;
String url = null;
Hashtable paramsTable;
public HttpMultipartRequest2(String url, Hashtable params,
String fileField, String fileName, String fileType, byte[] fileBytes) throws Exception
{
this.url = url;
String boundary = getBoundaryString();
paramsTable = params;
String boundaryMessage = getBoundaryMessage(boundary, params, fileField, fileName, fileType);
String endBoundary = "\r\n--" + boundary + "--\r\n";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write(boundaryMessage.getBytes());
bos.write(fileBytes);
bos.write(endBoundary.getBytes());
this.postBytes = bos.toByteArray();
bos.close();
}
String getBoundaryString() {
return BOUNDARY;
}
String getBoundaryMessage(String boundary, Hashtable params, String fileField, String fileName, String fileType)
{
StringBuffer res = new StringBuffer("--").append(boundary).append("\r\n");
Enumeration keys = params.keys();
while(keys.hasMoreElements())
{
String key = (String)keys.nextElement();
String value = (String)params.get(key);
res.append("Content-Disposition: form-data; name=\"").append(key).append("\"\r\n")
.append("\r\n").append(value).append("\r\n")
.append("--").append(boundary).append("\r\n");
}
res.append("Content-Disposition: form-data; name=\"").append(fileField)
.append("\"; filename=\"").append(fileName).append("\"\r\n")
.append("Content-Type: ").append(fileType).append("\r\n\r\n");
Log.info(("res "+res.toString()));
return res.toString();
}
public String send() throws Exception
{
StringBuffer sb = new StringBuffer();
HttpConnection hc = null;
InputStream is = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] res = null;
try
{
Log.info("before hc open"+ url);
hc = (HttpConnection) Connector.open(url);
hc.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + getBoundaryString());
hc.setRequestProperty("access_token", (String)paramsTable.get("access_token"));
hc.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, String.valueOf(postBytes.length));
hc.setRequestProperty( "x-rim-transcode-content", "none" );
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStream dos = hc.openOutputStream();
is = hc.openInputStream();
Log.info("before dos write responsecode");// + hc.getResponseCode());
out.write(postBytes, 0, postBytes.length);
//Log.info("flushing"+ hc.getResponseCode());
Log.info("after doswrite responsecode");
dos.write(out.toByteArray());
dos.flush();
Log.info("after flush");
if(dos!=null)
dos.close();
int ch;
Log.info("before openinput ");
Log.info("after openinput ");
while ((ch = is.read()) != -1)
{
bos.write(ch);
sb.append((char)ch);
Log.info("char"+(char)ch);
}
res = bos.toByteArray();
Log.info("Response recieved from Server is : " + sb.toString() );
}
catch(Exception e)
{
Log.info(hc.getResponseCode() + "sexce"+e);
}
catch(OutOfMemoryError error)
{
Log.info("outofmemory " + error);
System.gc();
}
finally
{
try
{
if(bos != null)
bos.close();
if(is != null)
is.close();
if(hc != null)
hc.close();
}
catch(Exception e2)
{
Log.info("finally exception"+ e2);
}
}
return sb.toString();
}
}
Are you trying to upload to a user's feed or to a page? There is an Open Bug regarding posting to pages.
Also, could you post some code?
Assuming that you've read the documentation:
Facebook Graph API->Video
And that you are using graph-video.facebook.com, not graph.facebook.com.
Related
I am new in AWS and Asp NetCore. Help me to find the solution.
I am using Asp NetCore, how should I use lambda function to upload clipped file in s3?
I have a IFormFile but I want to use s3 url instead of IFormFile and upload in s3 bucket. I have used ffmpeg library to cut the video and I want to send url of s3 using lambda function and upload the output of clipped video file again in s3 bucket directory that i created in s3 console.
using Abp.UI;
using FFmpeg.NET;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System;
using System.IO;
using Amazon.S3;
using System.Threading.Tasks;
using Amazon.S3.Transfer;
using Amazon.S3.Model;
using IdentityModel.Client;
using Amazon;
using System.Net.Http;
namespace VideoSlicer.About
{
public class AboutAppService : IAboutAppService
{
//Assigning readonly IHostingEnvironment
private readonly IHostingEnvironment _appEnvironment;
private readonly string bucketName = "videoslicerpuru";
private static readonly RegionEndpoint bucketRegion = RegionEndpoint.Region;
/*
private const string newFile = "QQ.mp4";
private const string newFile1 = "637156754716419260QQ.mp4";
private const string filePath = #"C:\Users\Purushottam\Downloads\VideoSlicer\5.1.1\aspnet-core\src\VideoSlicer.Web.Host\wwwroot\images\";*/
private static IAmazonS3 client;
//Making Constructor and passin IHostingEnvironment
public AboutAppService(IHostingEnvironment appEnvironment)
{
_appEnvironment = appEnvironment;
}
//Function which upload video and slice video accordingly start time and finish time given by the user
public async Task UploadImage(IFormFile file, string Start, string Finish)
{
HttpClient cli = new HttpClient();
cli.DefaultRequestHeaders.ExpectContinue = false;
try
{
//Taking out the extension of the file
var convertedExtension = file.FileName.Substring(file.FileName.LastIndexOf("."));
//Comparing the extension whether uploaded file is video or not
if (convertedExtension != ".mp4" && convertedExtension != ".flv" && convertedExtension != ".3GP" && convertedExtension != ".OGG" && convertedExtension != ".AVI" && convertedExtension != ".WMV ")
{
throw new UserFriendlyException("Please Select Valid Video file to clip!!");
}
//Checking if the file is null or has not been selected any file
if (file == null || file.Length == 0)
{
throw new UserFriendlyException("Please Select any file.");
}
//declaring web root path
string path_Root = _appEnvironment.WebRootPath;
//setting path root and saving video to the given path
string pathOfVideo = path_Root + "\\video\\";
string path_to_Video = path_Root + "\\images\\" + file.FileName;
using (var stream = new FileStream(path_to_Video, FileMode.Create))
{
await file.CopyToAsync(stream);
}
client = new AmazonS3Client("AccessKey", "SecretKey", bucketRegion);
TransferUtility utility = new TransferUtility(client);
TransferUtilityUploadRequest request = new TransferUtilityUploadRequest();
string nameOfFile = file.FileName.ToString();
string videoPath = path_to_Video.ToString();
await utility.UploadAsync(videoPath, bucketName, nameOfFile);
Console.WriteLine("Upload 2 completed");
//To cut video, using ffmpeg media file where the video is saved
var input = new MediaFile(path_to_Video);
//The output of the clipped video and saving in a different folder
string nameFile = DateTime.Now.Ticks + file.FileName;
string nameBucket = bucketName + "/videoslice/";
var output = new MediaFile(path_Root + "/video/" + nameFile);
client = new AmazonS3Client(bucketRegion);
//making the object of Engine using ffmpeg application file
var ffmpeg = new Engine("C:\\ffmpeg\\bin\\ffmpeg.exe");
//making object of Conversion Option of ffmpeg
var options = new ConversionOptions();
//Converting string to double
var startTime = Convert.ToDouble($"{Start}");
var finishTime = Convert.ToDouble($"{Finish}");
//clipping video by given user input
options.CutMedia(TimeSpan.FromSeconds(startTime), TimeSpan.FromSeconds(finishTime - startTime));
await ffmpeg.ConvertAsync(input, output, options);
string clipPath = path_Root + "\\video\\" + nameFile;
//Checking if start time is greater then finish time
if (startTime > finishTime)
{
throw new UserFriendlyException("Please Enter Valid Second to proceed");
}
//Checking if start time is equal to finish time
if (startTime == finishTime)
{
throw new UserFriendlyException("Please Enter Valid Second to proceed");
}
var a = utility.UploadAsync(clipPath, nameBucket, nameFile);
Console.WriteLine("Upload 2 completed");
}
catch (AmazonS3Exception e)
{
string err = e.Message;
throw e;
}
catch (InternalBufferOverflowException a)
{
string me = a.Message;
throw a;
}
catch (HttpRequestException c)
{
string error = c.Message;
throw c;
}
catch (DriveNotFoundException e)
{
string mes = e.Message;
throw e;
}
catch(NullReferenceException e)
{
throw new UserFriendlyException (500, "Please Select a file to proceed",e.Message);
}
}
}
}
can anyone check if there are error/s on my code: this is to pass byte for the microsoft speech api, however i received 400 bad request error. wav file format is correct since i used the sample from microsoft. any help would be appreciated!
public void speechToText(){
String Key = "mysubscriptionkey";
try {
File file = new File("filepath", "filename.wav");
URL url = new URL("https://westus.stt.speech.microsoft.com/speech/recognition/interactive/cognitiveservices/v1?langauge=en-US&format=simple");
HttpURLConnection con =(HttpURLConnection)url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
con.addRequestProperty("Content-type", "audio/wav; codec=\"audio/pcm\"; samplerate=16000");
con.addRequestProperty("Ocp-Apim-Subscription-Key", Key);
byte[] bytes = ReadFully(file);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.write(bytes);
Scanner scanner = new Scanner(con.getInputStream());
String responseBody = scanner.useDelimiter("\\A").next();
System.out.println(responseBody);
}
catch (Exception e)
{
e.printStackTrace();
}
--this one to read audio
public byte[] ReadFully(File file){
ByteArrayOutputStream out = new ByteArrayOutputStream();
try{
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[1024];
int bytesRead;
OutputStream outputstream ;
while ((bytesRead = in.read(buffer)) != -1){
out.write(buffer, 0, bytesRead);
}
}
catch (Exception e){
e.printStackTrace();
}
return out.toByteArray();
}
I am writing a web service in spring boot restful web App using which i am sending a image to anyone who wants to consume it below is a code snippet which worked for me
#RequestMapping(value = "/photo_1",method = RequestMethod.GET )
public ResponseEntity<byte[]> greeting_image_1(#RequestParam(value="name", defaultValue="World") String name) throws IOException{
InputStream in = getClass().getResourceAsStream("/images/someimage.jpg");
byte[] a = IOUtils.toByteArray(in);
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG);
return new ResponseEntity<byte[]>(a,headers,HttpStatus.CREATED);
}
This web service works perfectly fine in case i want to return a single image from a web service
But what if in case i want to return array of images(i.e. more than 1 image)
Any help is highly appreciated.
Regards,
Here's the sample code that I wrote to generate a multipart response with multiple images in it. It's properly consumed by Firefox and it prompts to save each image in the response.
public ResponseEntity<byte[]> showImages () throws IOException {
String boundary="---------THIS_IS_THE_BOUNDARY";
List<String> imageNames = Arrays.asList(new String[]{"1.jpg","2.jpg"});
List<String> contentTypes = Arrays.asList(new String[]{MediaType.IMAGE_JPEG_VALUE,MediaType.IMAGE_JPEG_VALUE});
List<Byte[]> imagesData = new ArrayList<Byte[]>();
imagesData.add(ArrayUtils.toObject(IOUtils.toByteArray(getClass().getResourceAsStream("/images/1.jpg"))));
imagesData.add(ArrayUtils.toObject(IOUtils.toByteArray(getClass().getResourceAsStream("/images/2.jpg"))));
byte[] allImages = getMultipleImageResponse(boundary, imageNames,contentTypes, imagesData);
final HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type","multipart/x-mixed-replace; boundary=" + boundary);
return new ResponseEntity<byte[]>(allImages,headers,HttpStatus.CREATED);
}
private static byte[] getMultipleImageResponse(String boundary, List<String> imageNames, List<String> contentTypes, List<Byte[]> imagesData){
byte[] finalByteArray = new byte[0];
Integer imagesCounter = -1;
for(String imageName : imageNames){
imagesCounter++;
String header="--" + boundary
+ "\r\nContent-Disposition: form-data; name=\"" + imageName
+ "\"; filename=\"" + imageName + "\"\r\n"
+ "Content-type: " + contentTypes.get(imagesCounter) + "\r\n\r\n";
byte[] currentImageByteArray=ArrayUtils.addAll(header.getBytes(), ArrayUtils.toPrimitive(imagesData.get(imagesCounter)));
finalByteArray = ArrayUtils.addAll(finalByteArray,ArrayUtils.addAll(currentImageByteArray, "\r\n\r\n".getBytes()));
if (imagesCounter == imageNames.size() - 1) {
String end = "--" + boundary + "--";
finalByteArray = ArrayUtils.addAll(finalByteArray, end.getBytes());
}
}
return finalByteArray;
}
You should implement this depending on the capability of the consumer. If the consumer can parse multipart response, please go ahead with this approach, else consider other options like
Sending a zipped file of all images
Returning a json/xml of image names along with URLs to download them
Returning a json/xml with all images in Base64 encoded string
You may also send a html response with all images embedded in it using the below code. This should work fine in all browsers as it is pure html.
public ResponseEntity<byte[]> getAllImages() throws IOException {
List<String> imageNames = Arrays.asList(new String[]{"1.jpg","2.jpg"});
List<String> contentTypes = Arrays.asList(new String[]{MediaType.IMAGE_JPEG_VALUE,MediaType.IMAGE_JPEG_VALUE});
List<Byte[]> imagesData = new ArrayList<Byte[]>();
imagesData.add(ArrayUtils.toObject(IOUtils.toByteArray(getClass().getResourceAsStream("/images/1.jpg"))));
imagesData.add(ArrayUtils.toObject(IOUtils.toByteArray(getClass().getResourceAsStream("/images/2.jpg"))));
byte[] htmlData=getHtmlData(imageNames,contentTypes, imagesData);
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_HTML);
return new ResponseEntity<byte[]>(htmlData,headers,HttpStatus.OK);
}
private static byte[] getHtmlData(List<String> imageNames, List<String> contentTypes, List<Byte[]> imagesData){
String htmlContent="<!DOCTYPE html><html><head><title>Images</title></head><body>";
Integer imagesCounter = -1;
for(String imageName : imageNames){
imagesCounter++;
htmlContent = htmlContent + "<br/><br/><b>" + imageName + "</b><br/></br/><img src='data:" + contentTypes.get(imagesCounter) + ";base64, " + org.apache.commons.codec.binary.StringUtils.newStringUtf8(Base64
.encodeBase64(ArrayUtils.toPrimitive(imagesData.get(imagesCounter)))) + "'/>";
}
htmlContent = htmlContent + "</body></html>";
return htmlContent.getBytes();
}
You should take a look to "Uploading Files" Spring Boot guide : https://spring.io/guides/gs/uploading-files/
There's a an example of upload and download.
I am calling a BPM web service that sends HTML email. I generated a web service proxy in JDeveloper 11.1.1.7. The type of the body of the email is xsd:string which should map to java String. I understand that certain characters, for example < > &, are reserved and converted during the xml document creation during the proxy operation.
Using SOAPUI to call the service, I can pass the body as <h1>My Heading</h1> and service responds correctly, sending the email with HTML as expected. When doing the same from a POJO that calls the proxy, <h1> is converted to <h1>My heading</h1>.
I have tried passing the body as a CDATA section but this makes no difference. I have tried converting the body to bytes then back to a UTF-8 string before the call but still no difference. I have access to the BPM service code. Is there a way I can send html to the service from a proxy, that retains the special characters?
I figured this out finally. While the JDeveloper web service proxy generator is useful most of the time, in this case it was not since I needed to send xml special characters to the service. Perhaps there is a way to manipulate the proxy code to do what you want but I couldn't figure it out.
Of particular help was this AMIS blog entry. And if you ever need to handle special characters during JAXB marshalling, this entry will help you too. A great summary of the steps to use the java URLConnection class is here and that answer points to a library that would probably make life even easier.
So here is the raw wrapper code below. The particular BPM email service we wrote also writes to a log and that explains the complex types in the raw xml input. Naturally I will populate the email values from a passed in POJO object in the main sendMail wrapper method.
package com.yourdomain.sendmail.methods;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import oracle.adf.model.connection.url.URLConnectionProxy;
import oracle.adf.share.ADFContext;
public class SendMailWrapper {
public SendMailWrapper() {
super();
}
public static void main(String[] args) throws MalformedURLException, IOException {
SendMailWrapper w = new SendMailWrapper();
w.sendMail();
}
public void sendMail() throws MalformedURLException, IOException {
String xmlInput =
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
"xmlns:sen=\"http://xmlns.oracle.com/bpmn/bpmnProcess/SendEmailProcess\" " +
"xmlns:ema=\"http://www.wft.com/BPM/SendEmail/Email\">\n" +
"<soapenv:Header/>" +
"<soapenv:Body>\n" +
"<sen:start>\n" +
"<ema:emailInput>\n" +
"<ema:emailContent>\n" +
"<ema:toAddr>your.name#yourdomain.com</ema:toAddr>\n" +
"<ema:fromAddr></ema:fromAddr>\n" +
"<ema:ccAddr></ema:ccAddr>\n" +
"<ema:bccAddr></ema:bccAddr>\n" +
"<ema:subject>SendMail HTML</ema:subject>\n" +
"<ema:body><h1>My Heading</h1><p>Text</p></ema:body>\n" +
"<ema:contentType>text/html</ema:contentType>\n" +
"</ema:emailContent>\n" +
"<ema:emailHistory>\n" +
"<ema:projectName>Soap Test</ema:projectName>\n" +
"<ema:reqID></ema:reqID>\n" +
"<ema:compositeID></ema:compositeID>\n" +
"<ema:processID></ema:processID>\n" +
"<ema:processName></ema:processName>\n" +
"<ema:activityName></ema:activityName>\n" +
"<ema:insertDate></ema:insertDate>\n" +
"<ema:insertByID></ema:insertByID>\n" +
"<ema:insertByName></ema:insertByName>\n" +
"<ema:commentType></ema:commentType>\n" +
"<ema:commentInfo></ema:commentInfo>\n" +
"</ema:emailHistory>\n" +
"</ema:emailInput>\n" +
"</sen:start>\n" +
"</soapenv:Body>\n" +
"</soapenv:Envelope>\n";
System.out.println(xmlInput);
String wsURL = getWsdlUrl();
URL url = new URL(wsURL);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection)connection;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buffer = new byte[xmlInput.length()];
buffer = xmlInput.getBytes();
bout.write(buffer);
byte[] b = bout.toByteArray();
String SOAPAction = "start"; //this is the method in the service
httpConn.setRequestProperty("Content-Length", String.valueOf(b.length));
httpConn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
//some other props available but don't need to be set...
//httpConn.setRequestProperty("Accept-Encoding", "gzip,deflate");
//httpConn.setRequestProperty("Host", "your.host.com:80");
//httpConn.setRequestProperty("Connection", "Keep-Alive");
//httpConn.setRequestProperty("User-Agent", "Apache-HttpClient/4.1.1 (java 1.5)");
httpConn.setRequestProperty("SOAPAction", SOAPAction);
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
OutputStream out = httpConn.getOutputStream();
out.write(b);
out.close();
//check response code...
int status = httpConn.getResponseCode();
String respMessage = httpConn.getResponseMessage();
System.out.println("RESPONSE CODE: " + status + " RESPONSE MESSAGE: " + respMessage);
//check response headers...
for (Map.Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
System.out.println(header.getKey() + "=" + header.getValue());
}
//check error stream - this helps alot when debugging...
InputStream errorStream = ((HttpURLConnection)connection).getErrorStream();
if (errorStream != null) {
System.out.println("Error Stream: " + convertStreamToString(errorStream));
}
//if there was an expected response, you need to parse it...
/* String responseString = "";
String outputString = "";
InputStreamReader isr = new InputStreamReader(httpConn.getInputStream());
BufferedReader in = new BufferedReader(isr);
while ((responseString = in.readLine()) != null) {
outputString = outputString + responseString;
}
isr.close();
System.out.println("OUT: " + outputString); */
}
static String convertStreamToString(InputStream is) {
Scanner s = new Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
private static String getWsdlUrl() {
String result = null;
try {
URLConnectionProxy wsConnection = (URLConnectionProxy)ADFContext.getCurrent().getConnectionsContext().lookup("SendMailProxyConnection");
result = wsConnection.getURL().toExternalForm();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
Happy coding.
I am implementing small Java ME app. This app gets some data from 3rd patty resource and needs to be authenticated before. I do first call for get cookies (it was easy), and the second call with this cookies for get data. I googled a little how to do it, and found next solution - Deal with cookie with J2ME
I have changed this code to next for my purpose:
public void getData(String url,String cookie) {
HttpConnection hpc = null;
InputStream is = null;
try {
hpc = (HttpConnection) Connector.open(url);
hpc.setRequestProperty("cookie", cookie);
hpc.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
hpc.setRequestProperty("Accept-Encoding", "gzip, deflate");
hpc.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
is = hpc.openInputStream();
int length = (int) hpc.getLength();
byte[] response = new byte[length];
is.read(response);
String strResponse = new String(response);
} catch (Exception e) {
System.out.println(e.getMessage() + " " + e.toString());
} finally {
try {
if (is != null)
is.close();
if (hpc != null)
hpc.close();
} catch (Exception e) {}
}
}
I get something like to the next
??ÑÁNÃ0à;O±(²§M}A-?#
.?PYS¨Ôe¥Í#\üìde??XÊo}Vâ]hk?6ëµóA|µvÞz'Íà?wAúêmw4í0?ÐÆ?ÚMW=?òêz CÛUa:6Ö7¼T?<oF?nh6[_0?l4?äê&)?çó³?ÅÕúf¨ä(.? ªDÙ??§?ÊP+??(:?Á,Si¾ïA¥ã-jJÅÄ8ÊbBçL)gs.S.þG5ÌÀÆéX}CÁíÑ-þ?BDK`²?\¶?ó3I÷ô±e]°6¬c?q?Ó?¼?Y.¯??Y?%?ÏP1è?ìw;?È Ò??e
|ôh0?
How can I decode this?
Stupid me. I didn't take to consideration next code: hpc.setRequestProperty("Accept-Encoding", "gzip, deflate"); I get coded in ZIP response and everything that I need it decode it.