How to set TimeOut while HTTP Connection in Android? - java

Hello I have this code from Androidhive:
It works well but I want to install a timeout - because sometimes if there is low connection it is loading for minutes so the app is crashing at the and (asynctask). so my question: how can I install a timeout into the following code? Let's say it shall timeout after 10 seconds?
thank u
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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;
}

Related

Error when trying to upload to database

Hey guys im trying to insert some data into a database from an android app, but the app crashes when trying to do so, i have the error log, but cant quite seem to figure out what it does. Can anyone please help me?
This is the error log: https://pastebin.com/Z8HmE21T
This is the code: https://pastebin.com/pCWaFniC
And this is my json parser
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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 do you get content from a HttpResponse in servlet?

I am currently learning to develop android application. I need to parse variables from my android application to the servlet. I use HttpResponse to parse the variables. But i do not know how to accept parameters in servlet.
This is my code in android application.
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://<ip_address>:8080/GetPhoneNumber/GetPhoneNumberServletServlet");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("phoneNum", "12345678"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} // End of onClick method
May I know what to do at the doPost/doGet in servlet?
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
out.println("Hello Android !!!!");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
In your doPost use request.getParameter("phoneNum").
I think the following code could help you.
public class CustomHttpClient
{
public static final int HTTP_TIMEOUT = 30 * 1000;
private static HttpClient mHttpClient;
private static HttpClient getHttpClient()
{
if (mHttpClient == null)
{
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
public static String executeHttpPost(String url,ArrayList<NameValuePair> postParameters) throws Exception
{
BufferedReader in = null;
try
{
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally
{
if (in != null)
{
try
{
in.close();
}
catch (IOException e)
{
Log.e("log_tag", "Error converting result "+e.toString());
e.printStackTrace();
}
}
}
}
public static String executeHttpGet(String url) throws Exception
{
BufferedReader in = null;
try
{
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally
{
if (in != null)
{
try
{
in.close();
}
catch (IOException e)
{
Log.e("log_tag", "Error converting result "+e.toString());
e.printStackTrace();
}
}
}
}
}
Addons:-
Use the JSON Parser class below:-
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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();
Log.d("json data",json.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;
}
}
Now if you want to send anything on the server, say you need to save the username and password on the server using the JSON Parser and PHP use the below code in any thread or in the doInBackground method of Async task.
ArrayList<NameValuePair> Insert = new ArrayList<NameValuePair>();
Insert.add(new BasicNameValuePair("User_Name","<Sting denoting username>"));
Insert.add(new BasicNameValuePair("Password","<Sting denoting Password>));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://server path/yourphpfile.php");
httppost.setEntity(new UrlEncodedFormEntity(Insert));
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());
}
Now if you need these values back using the get method in JSON Parser, user the following code again in the Thread or doInBackground method of Async task.
public class CountDownTask extends AsyncTask<Void,Void , Void>
{
protected void onPreExecute()
{
count = 0;
S_Store_Id = null; S_Store_Name = null;S_Store_Address = null; S_Store_Phone= null;
Offers = null; Descriptions = null;
}
protected Void doInBackground(Void... params)
{
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("User_Name",StringUserName));
String response = null;
try
{
response = CustomHttpClient.executeHttpPost("http://yourserverpath/yourphpfilefor retrivingdata.php",postParameters);
String result = response.toString();
try
{
JSONArray jArray = new JSONArray(result);
JSONObject json_data = jArray.getJSONObject(0);
StringUserName = json_data.getString("User_Name");
StringPassword = json_data.getString("Password");
json_data = jArray.getJSONObject(1);
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
catch (Exception e)
{
Log.e("log_tag","Error in http connection!!" + e.toString());
}
return null;
}
Now you can write the logic for inserting and retriving data from the server in your corresponding PHP files and use them for using data from the server. This method works equivalent to HTTP Get and Post methods of HTTP Request and Response.
Hope it can help you.. Thanks...

For each loop is not executing when uploaded at 000webhost server

I have an application that post data to a php file in an online server. When the post is done i get a garbage of html code. In it says I have a php error and that is Invalid argument supplied for each() on line 33. However this problem does not occur if I run it in localhost. I don't understand why this problem is occuring. So someone please help me to solve it.
The following is my jsonparser Class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getandpostJSONFromUrl(String url, String method,JSONArray name) {
// Making HTTP request
try {
// defaultHttpClient
if (method == "POST") {
HttpParams params = new BasicHttpParams();
//params.setParameter("data", auth);
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("json", name.toString()));
for (NameValuePair nvp : postParams) {
String name2 = nvp.getName();
String value = nvp.getValue();
Log.d("NameValue pair content", ""+name2+""+value);
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams,HTTP.UTF_8);
httpPost.setEntity(entity);
HttpResponse response = httpclient.execute(httpPost);
String responseBody = EntityUtils.toString(response.getEntity());
Log.d("",responseBody);
}
if (method == "GET") {
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();
}
if (method == "POST") {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
} catch (Exception e) {
Log.e("Buffer error", "Buffer error" + e);
}
} else if (method == "GET") {
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;
}
}
The following is the php file on the server
<?php
header('Content-type: application/json');
/*define('DB_NAME', 'a1422982_sshop');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');*/
define('DB_NAME', 'onlineshop');
define('DB_USER', 'shop');
define('DB_PASSWORD', 'pass');
define('DB_HOST', 'mysql28.000webhost.com');
$link = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
if(!$link){
die('could not connect: '.msql_error());
}
$db_selected=mysql_select_db(DB_NAME, $link);
if(!$db_selected){
die('Can not use '.DB_NAME.':'.mysql_error());
}
//var_dump(json_decode ($_POST['json'])));
if($_POST['json']){
$parsed = json_decode($_POST['json'],TRUE);
$i=0;
foreach ($parsed as $obj) {
$ProductName = $obj['Name'];
$ProductQuantity= $obj['Quantity'];
$sql="Update productlist Set Quantity='$ProductQuantity' where Name='$ProductName';";
$retval = mysql_query( $sql, $link );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
$i++;
echo $ProductName." ".$ProductQuantity;
}
}else{
echo "empty";
}
?>
there's a missing options on your HttpPost request set the entity metadata and the resulting entity as string.
In your java code you can do this:
Map<String, String> postData = new HashMap<String, String>();
postData.put("KEY", "yourvalue");
JSONObject holder = new JSONObject(postData);
StringEntity jsonStringEntity = new StringEntity(holder.toString());
httpost.setEntity(jsonStringEntity);
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
in that way your PHP code could actually parse your post data since json_decode() expecting json as parameter.

Using Hebrew on JSON code?

I am using this code to POST and GET data from MySQL database .
However when getting data that is not in English, it is displayed as question marks ?
what changes do I make to enable Hebrew language use ?
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
public JSONObject makeHttpRequest(String url, String method,List<NameValuePair> params) {
try {
if(method == "POST"){
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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 {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}
Make sure your HTTP response comes out encoded in Unicode (UTF-8 for example), and also your client (the application consuming the service) must be aware that of that encoding to read your response.

Parse Json Arabic text

I can't parse Arabic/Persian text from SQL database. Everything is set to UTF-8. My SQL database text is set to utf8_general_ci. JSON parser is set to UTF-8 too.
Text is shown good in English. But when I use Arabic/Persian text in database, android shows text as ???????.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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, "UTF-8"), 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;
}
}
I have been r & d around a day and finally success to parse my arabic json response getting from server using following code.So, may be helpful to you.
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
params.setBooleanParameter("http.protocol.expect-continue", false);
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httppost = new HttpPost(Your_URL);
HttpResponse http_response= httpclient.execute(httppost);
HttpEntity entity = http_response.getEntity();
String jsonText = EntityUtils.toString(entity, HTTP.UTF_8);
Log.i("Response", jsonText);
Now, use jsonText for your further requirement.
Thank You
Maybe the problem is on server side. Check the raw String you got from the Server to see if it is correctly formatted.
I think it can help you by storing it as clob/blob, since once you have the bytes which were convereted from UTF-8 at server side, any client side code can also then using various String encoding formats to display the test.
Or my other advice, use a webview to display it, its more mature to handle these nuances.

Categories