how to set request time out in Json Parser android - java

I have created the following function for getting json from server as below :
public class JSONParser {
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;
}
}
when user in bad connection, it just loading without give any notification, my question is : how can i add such as toast when request time out or bad connection?

I know, its been A long time, but I try to help, lets try to add this one :
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
HttpConnectionParams.setSoTimeout(httpParameters, 10000);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
and in your code, this will be :
try {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
HttpConnectionParams.setSoTimeout(httpParameters, 10000);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch(ConnectTimeoutException e){
Log.e("Timeout Exception: ", e.toString());
} catch(SocketTimeoutException ste){
Log.e("Timeout Exception: ", ste.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
and to show message request time out, you can add such as alert message on your onPostExecute() if the result null or empty.

First of all set HttpRequestTimeOut like given below then add this logic into try and catch and add toast message into catch block when request timeout fails it'll show you toast message.
url = new URI(s.replace(" ", "%20"));
Log.e("my webservice", "My webservice : " + url);
HttpGet httpget = new HttpGet(url);
HttpResponse httpResponse = null;
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is
// established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
// Execute HTTP Post Request
httpResponse = httpClient.execute(httpget);

Related

Getting a null pointer exception from my JSON parser

Error converting result java.lang.NullPointerException: lock == null
Error parsing data org.json.JSONException: End of input at character 0
of
can anyone tell me if whether this work?? I have connected my laptop with my wifi and mobile also with that. both having the same ipv4 address, and in the android code i have mentioned that address. How will my mobile know to contact the laptop where the database is stored?
This is my Android code JSON parser
public JSONObject makeHttpRequest(String url, String method,List<NameValuePair> params) {
try {
if(method.equals("POST"))
{
DefaultHttpClient httpClient = new DefaultHttpClient();
Log.e("herehai"," "+is);
HttpPost httpPost = new HttpPost(url);
Log.e("hereiam"," "+httpPost);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);//<-----Error is here
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
Log.e("here"," "+is);
}
else if(method.equals("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();
Log.e("here1"," "+is);
}
} 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.e("errors",json);
}
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 json string
return jObj;
}
Can someone tell me why is the null pointer exception is throwing up?
Try this
<?php
$con=mysqli_connect("localhost","root","") or die(mysql_error());
mysqli_select_db($con,"something")or die("Unable to connect 1");
$response = array();
$response["success"] = 0;
$email = $_POST['email'];
$passwd = $_POST['pass'];
$query1 = mysqli_query($con,"SELECT pass FROM userinfo where email='$email'");
$res= mysqli_fetch_assoc($query1);
if($res)
{
if($passwd!=$res['pass'])
{
$response["success"]=1;
print(json_encode($response));
}
else
{
$response["success"]=0;
print(json_encode($response));
}
}
else
{
$response["success"]=0;
print(json_encode($res));
}
?>

Android BasicNameValuePair with JSONObject as value

I am trying to send http POST request to local server
This is the code:
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);
httpStatusCode = httpResponse.getStatusLine().getStatusCode();
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = 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);
httpStatusCode = httpResponse.getStatusLine().getStatusCode();
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();
jsonString = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
try {
jsonObject = new JSONObject(jsonString);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data" + e.toString());
}
return jsonObject;
}
for the param I want to create a value pair as {"user": SOMEJSONObject} but current http POST only accept NameValuePair which only take string for values.
Create String entity instead:
httpPost.setEntity(new StringEntity("some string"));

Making a POST request in Android

I'm trying to make a POST request to a server in my Android app, but it ain't happening. Below is the code -
try{
View p = (View) v.getRootView();
EditText usernamefield = (EditText)p.findViewById(R.id.username);
String username = usernamefield.getText().toString();
EditText passwordfield = (EditText)p.findViewById(R.id.pass);
String password = passwordfield.getText().toString();
String apiKey = "ac96d760cb3c33a1ee988750b0b2fd12";
String secret = "cd9118e8d1d32d003e0ed54a202c2bf8";
Log.i(TAG,password);
String authToken = computeMD5hash(username.toLowerCase()).toString()+computeMD5hash(password).toString();
String authSig = computeMD5hash("api_key"+apiKey+"authToken"+authToken+"method"+"auth.getMobileSession"+"username"+username+secret).toString();
Log.i(TAG,authToken);
HttpClient client = new DefaultHttpClient();
Log.i(TAG,"after client1");
HttpPost post = new HttpPost("http://ws.audioscrobbler.com/2.0/");
Log.i(TAG,"after client2");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("method", "auth.getMobileSession"));
nameValuePairs.add(new BasicNameValuePair("api_key", apiKey));
nameValuePairs.add(new BasicNameValuePair("api_sig", authSig));
nameValuePairs.add(new BasicNameValuePair("format", "json"));
nameValuePairs.add(new BasicNameValuePair("authToken", authToken));
nameValuePairs.add(new BasicNameValuePair("username", username));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.i(TAG,post.getURI().toString()); //logs the URL
HttpResponse response = client.execute(post);
int status = response.getStatusLine().getStatusCode();
Log.i(TAG,"Status code is"+status);
Log.i(TAG,"after post");
InputStream ips = response.getEntity().getContent();
BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));
if(response.getStatusLine().getStatusCode()!= org.apache.commons.httpclient.HttpStatus.SC_OK)
{
Log.i(TAG,"bad http response");
Toast.makeText(getApplicationContext(),"bad httpcode",Toast.LENGTH_LONG).show();
throw new Exception(response.getStatusLine().getReasonPhrase());
}
StringBuilder sb = new StringBuilder();
String s;
while(true)
{
s = buf.readLine();
if(s==null || s.length()==0)
break;
sb.append(s);
}
buf.close();
ips.close();
System.out.print(sb.toString());
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
catch(NoSuchAlgorithmException e)
{
}
catch(Exception e){
}
The code executes till the Log.i(TAG,post.getURI().toString()) log statement. It'll print out the URL that is made - http://ws.audioscrobbler.com/2.0/. No parameters attached (which is weird).
I don't know what's wrong with my implementation for adding parameters to URL using NameValuePairs.
I do have one simple method to post data to server. Please use it and let me know if that is useful to you or not:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("method", "auth.getMobileSession"));
nameValuePairs.add(new BasicNameValuePair("api_key", apiKey));
nameValuePairs.add(new BasicNameValuePair("api_sig", authSig));
nameValuePairs.add(new BasicNameValuePair("format", "json"));
nameValuePairs.add(new BasicNameValuePair("authToken", authToken));
nameValuePairs.add(new BasicNameValuePair("username", username));
//call to method
JSONObject obj = makeHttpRequest(nameValuePairs, "http://ws.audioscrobbler.com/2.0/", "POST");
public static JSONObject makeHttpRequest(List<NameValuePair> params, String url, String method) {
InputStream is = null;
JSONObject jObj = null;
String json = "";
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
url = url.trim();
Log.e("FETCHING_DATA_FROM",""+url.toString());
HttpPost httpPost = new HttpPost(url);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 600000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 600000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
httpPost.setEntity(new UrlEncodedFormEntity(params,"utf-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
if(params!=null){
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
Log.e("FETCHING_DATA_FROM",""+url.toString());
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 600000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 600000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
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 jObj;
}
You must have wrapped this code in a try catch block since there are several possible exceptions thrown here. As to which is the problem I am not sure, but here are some common ones that could cause a problem and you need to give more info before we can see which one it is:
1) On newer versions of Android if you make thisw call in the main UI thread it will throw an exception a NetworkOnMainThread exception. You must do networking code on a background thread.
2) You did not declare the Internet permission in your manifest so it will throw a security exception.
You need to look at the logcat for an exception or break in the catch part of your try/catch. If your catch looks like this:
catch(Exception e)
{
}
Then it will silently eat the exception and give you no indication of the problem.
Just try with JsonStringer.Like:
HttpPost request = new HttpPost("http://ws.audioscrobbler.com/2.0/something_here");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
JSONStringer vm;
try {
vm = new JSONStringer().object().key("method")
.value("auth.getMobileSession").key("api_key").value(apikey)
.key("api_sig") .value(authSig).key("format").value("json").key(authToken).value(authToken).key("username").value(username)
.endObject();
StringEntity entity = new StringEntity(vm.toString());
request.setEntity(entity);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
Also as Kaediil said make try and catch clause with your response code.

android get data from server to client error

My application will connect to the server, and receive information about the server returns json format. But when I used httpclient and pick up information returns a null value. please help me fix this.
Returns Information on server
{"token":"05940d1d5d764068816fdef1da1cc2e1","firstName":"Hà Duy","lastName":"Đinh","permission":["ADMIN_ORG","SHOOTING","MANAGE_IMAGE","PHOTOGRAPHER","IMAGE_PROCESSING","BUYER","PRODUCT_MANAGER","ADMIN_ORG","SHOOTING","MANAGE_IMAGE","PHOTOGRAPHER","IMAGE_PROCESSING","BUYER","PRODUCT_MANAGER"]}
My url
http://testing.lvsolution.vn:9876/cloudbizws/rest/auth/1039&haduy#lvsolution.vn&123456
My code
private HttpResponse doResponse(String url) {
HttpResponse response = null;
try
{
HttpClient Client = new DefaultHttpClient();
URI website = new URI(url);
HttpGet request = new HttpGet();
request.setURI(website);
response = Client.execute(request);
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
return response;
}
you can do this code it will surely work
String json = "";
HttpResponse response = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(uri));
response = client.execute(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
json = reader.readLine();
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try this one:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url); // or GET
HttpResponse resp = client.execute(post);
InputStream is = resp.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
is.close();
To be sure the server send the response try to call the URL from the browser

App crashes on httGet when attempting to send to Json?

My app crashes on "((HttpResponse) httpGet).setEntity(new StringEntity(jo.toString(),"UTF-8"));" and throws an exception "java.lang.ClassCastException:org.apache.http.client.methods.HttpGet".
JSONObject jo = new JSONObject();
try {
jo.put("devicetoken", devicetoken);
URI uri = new URI("http", "praylistws-dev.elasticbeanstalk.com",
"/rest/list/myprayerlist/"+Helper.email, null, null);
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(uri);
// Prepare JSON to send by setting the entity
((HttpResponse) httpGet).setEntity(new StringEntity(jo.toString(),
"UTF-8"));
// Set up the header types needed to properly transfer JSON
httpGet.setHeader("Content-Type", "application/json");
httpGet.setHeader("Accept-Encoding", "application/json");
httpGet.setHeader("Accept-Language", "en-US");
// Execute POST
response = httpClient.execute(httpGet);
String string_response = EntityUtils.toString(response.getEntity());
string_resp = string_response += "";
} catch (Exception ex) {
ex.printStackTrace();
}
save(string_resp);
return result;
Activity{
oncreate{
new HitService().execute(addparams here);
}
}
protected String doInBackground(String... params) {
String result = null;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://your url=" + params[0]);
HttpResponse response;
try {
response = httpClient.execute(httpGet);
result = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
If you want to put some data to request body, you have to use HttpPost instead of HttpGet. HttpPost has function for this: setEntity(HttpEntity entity)
Example:
JSONObject jo = new JSONObject();
try {
jo.put("devicetoken", devicetoken);
URI uri = new URI("http", "praylistws-dev.elasticbeanstalk.com",
"/rest/list/myprayerlist/"+Helper.email, null, null);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(uri);
// Prepare JSON to send by setting the entity
httpPost.setEntity(new StringEntity(jo.toString(), "UTF-8"));
// Set up the header types needed to properly transfer JSON
httpGet.setHeader("Content-Type", "application/json");
httpGet.setHeader("Accept-Encoding", "application/json");
httpGet.setHeader("Accept-Language", "en-US");
// Execute POST
HttpResponse response = httpClient.execute(httpPost);
String string_response = EntityUtils.toString(response.getEntity());
string_resp = string_response += "";
} catch (Exception ex) {
ex.printStackTrace();
}
save(string_resp);
return result;

Categories

Resources