How to send httpRequest to server with GZIP DATA - java

I have a json file that I am sending to the server as a POST but it has to be gzipped
I dont know how to do it
I found the potential solution here GZip POST request with HTTPClient in Java
but I dont know how to merge the methodology they used in the second part of the answer with my makeHttpRequest method (they are using a multipart entity and Im using a urlencoded entity)
EDIT: Here is how I get jsonAsBytes
public static byte[] stringToGZIPByteArray (String string) {
Log.d("string to be gzipped", string);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null;
try {
gzos = new GZIPOutputStream(baos);
gzos.write(string.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (gzos != null) {
try {
gzos.close();
} catch (IOException ignore) {
};
}
}
return baos.toByteArray();
} // End of stringToGZIPByteArray
This is where I use that method
jsonParser.sendGzippedJSONviaHTTP(context, API.JSON_ACCEPT, UtilityClass.stringToGZIPByteArray(jsonObject.toString()), context.getResources());
and this is sendGzippedJSONviaHTTP
public JSONObject sendGzippedJSONviaHTTP(Context context, String url, byte[] gzippedJSON, Resources res) {
if (httpClient == null) {
try {
httpClient = new HttpClientBuilder().setConnectionTimeout(10000)
.setSocketTimeout(60000) //
.setHttpPort(80)//
.setHttpsPort(443)//
.setCookieStore(new BasicCookieStore())//
.pinCertificates(res, R.raw.keystore, null) //
.build();
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// Making HTTP request
try {
// request method is POST
// defaultHttpClient
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Encoding", "gzip");
httpPost.setHeader("Content-Type", "application/json");
httpPost.setEntity(AndroidHttpClient.getCompressedEntity(gzippedJSON, context.getContentResolver()));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
reader.close();
json = sb.toString();
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jsonObject = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
// return JSON String
return jsonObject;
} // End of makeHttpRequest

Take a look at AndroidHttpClient. You can use it instead of appache's DefaultHttpClient. It has a static method getCompressedEntity(byte[] data, ContentResolver resolver)
So, you can write:
HttpPost httpPost = new HttpPost(url);
post.setEntity( AndroidHttpClient.getCompressedEntity( jsonAsBytes, null ) );
httpClient.execute(httpPost);
UPDATE:
this is the code from AndroidHttpClient:
public static AbstractHttpEntity getCompressedEntity(byte data[], ContentResolver resolver)
throws IOException {
AbstractHttpEntity entity;
if (data.length < getMinGzipSize(resolver)) {
entity = new ByteArrayEntity(data);
} else {
ByteArrayOutputStream arr = new ByteArrayOutputStream();
OutputStream zipper = new GZIPOutputStream(arr);
zipper.write(data);
zipper.close();
entity = new ByteArrayEntity(arr.toByteArray());
entity.setContentEncoding("gzip");
}
return entity;
}
should give you some insights

Related

why i am getting org.json.JSONException: Value property of type java.lang.String cannot be converted to JSONObject?

By use of this i'm getting response code and trying to convert String to JSONObject but getting exception.
public JSONObject getJSONFromUrl(String url,List<NameValuePair> nameValuePairsList) {
// Making HTTP request
try {
HttpParams param = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(param, 20000);
HttpConnectionParams.setSoTimeout(param, 20000);
DefaultHttpClient httpClient = new DefaultHttpClient(param);
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairsList));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
PropertyLogger.debug("URL Request: ", url.toString());
PropertyLogger.debug("Encoded Params: ", nameValuePairsList.toString());
HttpResponse httpResponse = httpClient.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
if (code != 200) {
PropertyLogger.debug("HTTP response code is:", Integer.toString(code));
return null;
} else {
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (ConnectTimeoutException e) {
// TODO: handle exception
PropertyLogger.error("Timeout Exception", e.toString());
return null;
} catch (SocketTimeoutException e) {
// TODO: handle exception
PropertyLogger.error("Socket Time out", e.toString());
return null;
} catch (UnsupportedEncodingException e) {
PropertyLogger.error("UnSupported Exception", e.toString());
e.printStackTrace();
return null;
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
String TAG = "PropertyJsonParser";
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
jsonResp = sb.toString();
PropertyLogger.debug("Content: ", sb.toString());
} catch (Exception e) {
PropertyLogger.error("Buffer Error", "Error converting Response " + e.toString());
return null;
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(jsonResp);
} catch (JSONException e) {
PropertyLogger.error("JSON Parser", "Error parsing data :" + e.toString());
return null;
}
return jObj;
}
You get this error because you are not receiving proper JSON response.
Check your api response and possible also provide your api response.
Because your variable jsonResp contain string value not JSONObject so please first print and make sure is it string type value or not.

How to Convert string to JSON Object?

I am using following code to deserailze the JSON data from Url.
But My Error is:Value {"InvoiceNo":18} of type java.lang.String cannot be converted to JSONObject.My Json Like: "{\"InvoiceNo\":18}" Please Any one Help me.
private class LongOperation extends AsyncTask{
#Override
protected Object doInBackground(Object[] params) {
HttpResponse response = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(
"http://192.168.1.2/Json/api/test"));
response = client.execute(request);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String responseText = null;
try {
responseText = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
try {
JSONObject json = new JSONObject(responseText); // **Error on this line**
Iterator<String> keys = json.keys();
while (keys.hasNext()) {
String key = keys.next();
String value = null;
try {
value = json.getString(key);
Toast.makeText(Billing.this, value + "",
Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
textInvoice.setText(value.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("responseText", responseText);
return null;
}
}
Your String should not contain the character "\". If so, this is the cause of your problem.

jsonparse android get data from server secure with login/password

I want to get the data ["04:44","05:59","12:03","15:29","18:07","18:07","19:17"]
from a server that is secure with login and password.
I already have the code for get the datajson:
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
How can I
connect with the server and
how can I get the data from jObj?

How to get Java script variable from HTML using HttpClient

I need to get the js variable from HTML. I get html from server using HttpCLient, and try to search "src" in stringBuilder.
I want to get image URL shown on page.
Thml sting that i parsed.
How to get this variable?
< img id="h5" src="8.jpg" border="0">
#Override
protected String doInBackground(Void... params) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 30 * 1000);
HttpConnectionParams.setSoTimeout(httpParameters, 30 * 1000);
httpclient = new DefaultHttpClient(httpParameters);
httpGet = new HttpGet(url);
httpGet.setHeader("Accept-Encoding", "gzip");
//Запрос
HttpResponse response = null;
try {
response = httpclient.execute(httpGet);
} catch (IOException e) {
e.printStackTrace();
}
InputStream instream = null;
try {
instream = response.getEntity().getContent();
} catch (IOException e) {
e.printStackTrace();
}
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if ((contentEncoding != null) && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
try {
instream = new GZIPInputStream(instream);
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(instream, "utf-8"), 8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
if (line.contains("\" src"))
{
sb.append(line).append("\n");
}}
} catch (IOException e) {
e.printStackTrace();
}
try {
instream.close();
} catch (IOException e) {
e.printStackTrace();
}
String result = sb.toString();
Log.i("Do id back", " ");
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
txtUrl.setText(result.toString());
Log.i("on Post"," ");
}
}
You can use an HTML parser, e.g. jsoup.

How to get Audio file through HTTP get?

I am trying to get an Audio file through http get from a secure restful service, I have successfully receive and parse text XML service but a bit confused that how to do with Audio file.
code to call the secure restful service with XML response
String callWebService(String serviceURL) {
// http get client
HttpClient client = getClient();
HttpGet getRequest = new HttpGet();
try {
// construct a URI object
getRequest.setURI(new URI(serviceURL));
} catch (URISyntaxException e) {
Log.e("URISyntaxException", e.toString());
}
// buffer reader to read the response
BufferedReader in = null;
// the service response
HttpResponse response = null;
try {
// execute the request
response = client.execute(getRequest);
} catch (ClientProtocolException e) {
Log.e("ClientProtocolException", e.toString());
} catch (IOException e) {
Log.e("IO exception", e.toString());
}
try {
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
} catch (IllegalStateException e) {
Log.e("IllegalStateException", e.toString());
} catch (IOException e) {
Log.e("IO exception", e.toString());
}
StringBuffer buff = new StringBuffer("");
String line = "";
try {
while ((line = in.readLine()) != null) {
buff.append(line);
}
} catch (IOException e) {
Log.e("IO exception", e.toString());
return e.getMessage();
}
try {
in.close();
} catch (IOException e) {
Log.e("IO exception", e.toString());
}
// response, need to be parsed
return buff.toString();
}
may this one help you..
public static void downloadFile(String fileURL, String fileName) {
try {
// fileURL=fileURL.replaceAll("amp;", "");
Log.e(fileURL, fileName);
String RootDir = Environment.getExternalStorageDirectory()
.toString();
File RootFile = new File(RootDir);
new File(RootDir + Commons.dataPath).mkdirs();
File file = new File(RootFile + Commons.dataPath + fileName);
if (file.exists()) {
file.delete();
}
file.createNewFile();
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File(
"mnt/sdcard"+Commons.dataPath + fileName));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Categories