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.
Related
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?
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));
}
?>
Sorry for my english. I cant send json to server. I have error:
{"message":"Customer data is empty!","status":"error"}
Its my example, hov i must send json:
JSON example:
{
"company_id": "1",
"phones": [
"380000505050"
],
"photo": "/files/clients_photos/tmp/484629825.JPG",
"name": "sdfsdfdsf",
"birthdate": "10.02.2014",
"email": "sdf#sdf.ff",
"cars": {
"1": {
"car_brand_id": "9",
"car_model_id": "856",
"number": "AE5884AH",
"photo": "/files/clients_photos/tmp/484629824.JPG"
}
}
}
This is link, where i send json http://crm.pavlun.info/api/register
This is my code:
protected Void doInBackground(String... params) {
JSONParser operationLink = new JSONParser();
ArrayList<NameValuePair> postInform = new ArrayList<NameValuePair>();
postInform.add(new BasicNameValuePair("company_id", "2"));
postInform.add(new BasicNameValuePair("phones", "380950466589"));
postInform.add(new BasicNameValuePair("name", "Alexy"));
postInform.add(new BasicNameValuePair("birthdate", "12.03.2014"));
postInform.add(new BasicNameValuePair("email", "nesalexy#mail.ru"));
postInform.add(new BasicNameValuePair("photo", "/files/clients_photos/tmp/484629825.JPG"));
JSONObject registration = null;
try {
Log.e("perform link", postInform.toString()); //its output [company_id=2, phones=380950466589, name=Alexy, birthdate=12.03.2014, email=nesalexy#mail.ru, photo=/files/clients_photos/tmp/484629825.JPG]
registration = operationLink.makeHttpRequest(registrationURL, "POST", postInform);
Log.e("Link", registration.toString()); //its output {"message":"Customer data is empty!","status":"error"}
}catch(Exception e) {
e.printStackTrace();
}
return null;
}
This is JSONparser class:
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) throws JSONException {
// 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, HTTP.UTF_8));
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;
//return new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
}
}
I believe I had the same problem previously, strangely enough, servers differ in the way they accept post data.
here is an example
the following method works for a jetty server but not Play:
public static void sendPost(String data,String url) throws Exception{
org.apache.http.impl.client.DefaultHttpClient client = new org.apache.http.impl.client.DefaultHttpClient();
org.apache.http.client.methods.HttpPost post = new org.apache.http.client.methods.HttpPost(url);
org.apache.http.entity.StringEntity entity = new org.apache.http.entity.StringEntity(data.toString());
post.setEntity(entity);
client.execute(post);
}
the followig method works for Play server but not jetty:
public static void sendPostV2(String data, String url) throws Exception{
org.apache.commons.httpclient.HttpClient client =
new org.apache.commons.httpclient.HttpClient();
org.apache.commons.httpclient.methods.PostMethod method =
new org.apache.commons.httpclient.methods.PostMethod(url);
method.addParameter("data", data);
client.executeMethod(method);
method.releaseConnection();
}
we still haven't figured out why, but oh well whatever works baby.
in your case please feel free to use any of the following method (note download the required apache packages). hopefully one of them works for you.
NODE.js : (zip the file)
app.post('/api/db', function(req, res){
if(req.body.type == 'Control'){
var zip = new AdmZip();
console.log(req.body.type);
zip.addLocalFolder(__dirname +'/XXX/Temp/1');
var willSendthis = zip.toBuffer();
zip.writeZip(__dirname +'/files.zip');
res.sendFile(zip);
}
});
JAVA : (send a request to want to zip file)
public class HttpAsyncTask extends AsyncTask<String, Void, String> {
public ArrayList<String> aList= new ArrayList<String>();
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("type", "Control"));
JSONObject json = jsonParser.makeHttpRequest(url, type, params);
Log.d("Create Response", json.toString());
return null;
}
protected void onPostExecute(String result) {
}
}
JSON PARSER:
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));
for (NameValuePair nvp : params){
Log.d("parameter", nvp.getName());
Log.d("parameter", nvp.getValue());
}
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "PUT"){
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPut httpPut = new HttpPut(url);
httpPut.setEntity(new UrlEncodedFormEntity(params));
for (NameValuePair nvp : params){
Log.d("parameter", nvp.getName());
Log.d("parameter", nvp.getValue());
}
HttpResponse httpResponse = httpClient.execute(httpPut);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "DELETE"){
DefaultHttpClient httpClient = new DefaultHttpClient();
String param = null;
for (NameValuePair nvp : params){
param = nvp.getValue();
url += "/" + param;
Log.d("url = ", url);
}
url = url.trim();
Log.d("url = ", URLEncoder.encode(url, "UTF-8"));
HttpDelete httpDelete = new HttpDelete(url);
HttpResponse httpResponse = httpClient.execute(httpDelete);
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-9"), 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 sent .zip file from server to android devices. I want to save into the android devices memory.
How can i save .zip file which is sended by node.js server?
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"));