android get data from server to client error - java

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

Related

SSLException - Hostname in certificate didn't match

I get this exception
javax.net.ssl.SSLException: hostname in certificate didn't match: <domain.com> != <*.hostgator.com> OR <*.hostgator.com> OR <hostgator.com>
when I use this JSON Parser:
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, "utf-8"));
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, Charset.forName("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) {
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
}
return jObj;
}
}
Does anyone know how to solve this?
On some devices it's working normally like on Galaxy S6 running Android 6.0.1, but on most other devices I get error.
Why some devices have problems with it and others don't?

pass parameters via http post method

I have two text boxes, 1 for username and the other for password.
I wanted to pass what the user enters into the edit texts with the post method
String request = "https://beta135.hamarisuraksha.com/web/webservice/HamariSurakshaMobile.asmx/getIMSafeAccountInfoOnLogon";
URL url;
try {
url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;");// boundary="+CommonFunctions.boundary
connection.setUseCaches(false);
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = connection.getResponseCode();
/*
* System.out.println("\nSending 'POST' request to URL : " +
* url); System.out.println("Post parameters : " +
* urlParameters);
*/
System.out.println("Response Code : " + responseCode);
InputStream errorstream = connection.getErrorStream();
BufferedReader br = null;
if (errorstream == null) {
InputStream inputstream = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(inputstream));
} else {
br = new BufferedReader(new InputStreamReader(errorstream));
}
String response = "";
String nachricht;
while ((nachricht = br.readLine()) != null) {
response += nachricht;
}
// print result
// System.out.println(response.toString());
return response.toString();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
if i am getting your question correctly , you need to pass your parameters to a web service. in my case i have implemented a method to get the web service response by giving the url and the values as parameters. i think this will help you.
public JSONObject getJSONFromUrl(JSONObject parm,String url) throws JSONException {
InputStream is = null;
JSONObject jObj = null;
String json = "";
// Making HTTP request
try {
// defaultHttpClient
/*JSONObject parm = new JSONObject();
parm.put("agencyId", 27);
parm.put("caregiverPersonId", 47);*/
/* if(!(jObj.isNull("d"))){
jObj=null;
}
*/
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
HttpEntity body = new StringEntity(parm.toString(), "utf8");
httpPost.setEntity(body);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
/* String response = EntityUtils.toString(httpEntity);
Log.w("myApp", response);*/
} 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());
}
// JSONObject jObj2 = new JSONObject(json);
// 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;
}
this method take two parameters. one is the url, other one is the values that we should send to the web service. and simply returns the json object. hope this will help you
EDIT
to pass your username and password just use below code
JsonParser jp = new JsonParser(); // create instance for the jsonparse class
String caregiverID = MainActivity.confirm.toString();
JSONObject param = new JSONObject();
JSONObject job = new JSONObject();
try {
param.put("username", yourUserNAme);
job = jp.getJSONFromUrl(param, yourURL);

how to set request time out in Json Parser android

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);

HttpClient.excute(HttpPost) no response

I constructed an HttpClient, and set timeout parameters.
the code is like this:
while(bufferedinputstream.read()!=-1){
post.setEntity(multipartEntity);
HttpResponse response = httpClient.excute(post);
}
it worked fine for the first several request, and then somehow the response is not returned, and no exception or timeout exception was thrown. Anyone has any idea what's happening?
since you re not getting any errors or exceptions (do you print them out?), you could check the satusCode of your response. Maybe it helps.
(overridden method from my AsyncTask)
protected String doInBackground(String... arg) {
String url = arg[0]; // Added this line
//...
Log.i(DEBUG_TAG, "URL CALL -> " + url);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
String mResponse = "";
try {
List<NameValuePair> params = new LinkedList<NameValuePair>();
//...
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse mHTTPResponse = client.execute(post);
StatusLine statusLine = mHTTPResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { //
//get response
BufferedReader rd = new BufferedReader(new InputStreamReader(
mHTTPResponse.getEntity().getContent()));
StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = rd.readLine()) != null) {
builder.append(aux);
}
mResponse = builder.toString();
} else {
//cancel task and show error
Log.e(DEBUG_TAG, "ERROR in Request:" + statusCode);
this.cancel(true);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return mResponse;
}

Android : JSON Parser with async task (GET and POST methods)

Just want to check whether this JSON Parser with async task is it correctly done? When I put this code into my Eclipse, this (method.equals("POST") was underline red. And it state that the 'method' cannot be solved. Any suggestion or help in this? Thank you.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
String url=null;
List<NameValuePair> nvp=null;
// 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) {
BackGroundTask Task= new BackGroundTask(url, method, params);
try {
return Task.execute().get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public class BackGroundTask extends AsyncTask<String, String, JSONObject>{
List<NameValuePair> postparams= new ArrayList<NameValuePair>();
String URL=null;
public BackGroundTask(String url, String method, List<NameValuePair> params) {
URL=url;
postparams=params;
}
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
// Making HTTP request
try {
// Making HTTP request
// check for request method
if(method.equals("POST")){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(postparams));
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(postparams, "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;
}
}
}
You forgot to declare method property in your BackGroundTask class.
EDIT Like this:
public class BackGroundTask extends AsyncTask<String, String, JSONObject>{
List<NameValuePair> postparams= new ArrayList<NameValuePair>();
String URL=null;
String method = null;
public BackGroundTask(String url, String method, List<NameValuePair> params) {
URL=url;
postparams=params;
this.method = method;
}
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
// Making HTTP request
try {
// Making HTTP request
// check for request method
if(method.equals("POST")){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(postparams));
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(postparams, "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;
}
}
}
You need to set method as a class variable within BackGroundTask. You are passing it into the constructor but not going anything with it. Set it the same way you have done with url and postparams.

Categories

Resources