I am trying to use httpurlconnection to post parameters to URL. The httpurlconnection seems to be posting fine when posting values without spaces however the issue appears when something like submit=Login Accountwhich contains a space. I have tried to use a plus symbol and %20 instead of the space however I have been unsuccessful submitting the form.
String requestParameters =“password=test123&confirm=test123&id=2869483&submit=Login Account”;
posting function
public static String postURL(String urlString, String parameters, int timeout, Proxy proxy, String accept, String acceptEncoding, String userAgent, String acceptLanguage) throws IOException {
URL address = new URL(urlString);
HttpURLConnection httpConnection = (HttpURLConnection) address.openConnection(proxy);
httpConnection.setRequestMethod("POST");
httpConnection.addRequestProperty("Accept", accept);
httpConnection.addRequestProperty("Accept-Encoding", acceptEncoding);
httpConnection.addRequestProperty("User-Agent", userAgent);
httpConnection.addRequestProperty("Accept-Language", acceptLanguage);
httpConnection.addRequestProperty("Connection", "keep-alive");
httpConnection.setDoOutput(true);
httpConnection.setConnectTimeout(timeout);
httpConnection.setReadTimeout(timeout);
DataOutputStream wr = new DataOutputStream(httpConnection.getOutputStream());
wr.writeBytes(parameters);
wr.flush();
wr.close();
httpConnection.disconnect();
BufferedReader in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
StringBuffer response = new StringBuffer();
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
String result = response.toString();
in.close();
return result;
}
request to post using posting function
*
ArrayList<unlock> ns = new ArrayList<>();
try {
ns = methods.UnlockRequest("register#test.com");// gets urls from database.
} catch (IOException e) {
e.printStackTrace();
}
String s = ns.get(0).toString(); // gets first url in list
url=s; // sets url to s
String[] st= url.split("id="); // splits url to get id
System.out.println(url);
System.out.println(st[1]);
System.out.println("accounts class reached");
String requestParameters = null;
requestParameters = "password=test123&confirm=test123&id=2869483&submit=Login Account”;
System.out.println(requestParameters);
ConnectionSettings connectionSettings = Variables.get().getConnectionSettings();
String creation = "";
System.out.println(Variables.get().getCaptchaSolution());
try {
if (connectionSettings.isProxyCreation()) {
creation = HTTPRequests.postURL(url, requestParameters, 30000, connectionSettings.getProxy(), connectionSettings.getAcceptCriteria(), connectionSettings.getAcceptEncoding(),
connectionSettings.getUserAgent(), connectionSettings.getAcceptLanguage());
}
} catch (FileNotFoundException e) {
System.out.println(ColoredText.criticalMessage("Error: Your IP is banned from requesting. Ending script."));
Variables.get().setStopScript(true);
} catch (IOException e) {
e.printStackTrace();
Variables.get().setStopScript(true);
}
*
Related
I am capturing a live image using JavaScript and storing that image in the database in encrypted form. Below is the code for storing image in database.
Session["imageName"] = DateTime.Now.ToString("dd-MM-yy hh-mm-ss");
Session["imagePath"] = string.Format("{0}.png", Session["imageName"].ToString());
Session["CapturedImage"] = ResolveUrl(Session["imagePath"].ToString());
private static byte[] ConvertHexToBytes(string hex)
{
byte[] bytes = new byte[hex.Length * sizeof(char)];
System.Buffer.BlockCopy(hex.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
public static bool SaveCapturedImage(string data)
{
string url = HttpContext.Current.Session["CapturedImage"].ToString();
HttpContext.Current.Session["CapturedImage"] = null;
return true;
}
protected void btnUpload_Click1 (object sender, EventArgs e)
{
using (StreamReader reader = new StreamReader(Request.InputStream))
{
Session["hexString"] = Server.UrlEncode(reader.ReadToEnd());
string filename = Session["imageName"].ToString();
string contentType = Session["imagePath"].ToString();
using (FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write))
{
byte[] bytes = ConvertHexToBytes(Session["hexString"].ToString());
string constr = ConfigurationManager.ConnectionStrings["Con2"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "insert into tblFiles values (#UId,#Name, #RelativeName, #ImageName, #ContentType, #Data, #uname)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#UId", txtId.Text);
cmd.Parameters.AddWithValue("#Name", txtName.Text);
cmd.Parameters.AddWithValue("#RelativeName", txtRName.Text);
cmd.Parameters.AddWithValue("#ImageName", filename);
cmd.Parameters.AddWithValue("#ContentType", contentType);
cmd.Parameters.AddWithValue("#Data", bytes);
cmd.Parameters.AddWithValue("#uname", Session["uname"].ToString());
con.Open();
cmd.ExecuteNonQuery();
con.Close();
this.clear();
}
}
}
}
}
How can I decrypted the image on page load at next page. I have tried many things but am not able to do it.
Thanks.
I wrote a Java program which generates HMAC SHA hash code, But due to some reason I have to write the same code in NodeJs/JavaScript. I tried googling around but did not get anything. In this Java code, I am passing URI and Key as arguments, to generate the hash code, where URI contains Timestamp.
The java code is as :
public static String calcMAC(String data, byte[] key) throws Exception {
String result=null;
SecretKeySpec signKey = new SecretKeySpec(key, SecurityConstants.HMAC_SHA1_ALGORITHM);
Mac mac = Mac.getInstance(SecurityConstants.HMAC_SHA1_ALGORITHM);
mac.init(signKey);
byte[] rawHmac;
try {
rawHmac = mac.doFinal(data.getBytes("US-ASCII"));
result = Base64.encodeBase64String(rawHmac);
} catch (Exception e) {
e.printStackTrace();
}
return result.trim();
}
public static void main(String args[]) {
String timestamp = args[0];
String key = "d134hjeefcgkahvg32ajkdbaff84ff180";
String out = null;
try {
out = calcMAC("/req?app_id=47ca34" + timestamp + "=2018-05-22T12:02:15Z",
key.getBytes());
System.out.println(URLEncoder.encode(out, "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
}
Is it possible to achieve the same goal in NodeJs/JavaScript?
Note:: I have to call this script from Postman pre-request script.
The crypto module should do this for you, you can substitute the 'data' variable with whatever you want to hash:
const crypto = require('crypto');
const data = 'The fault dear Brutus lies not in our stars';
const key = Buffer.from('d134hjeefcgkahvg32ajkdbaff84ff180', 'utf8');
const hash = crypto.createHmac('sha1', key).update(data).digest('base64');
const uriEncodedHash = encodeURIComponent(hash);
console.log('Hash: ' + uriEncodedHash);
Hashing the data in both Java and Node.js gives me the result (URI Encoded) of:
TJJ3xj93m8bfVpGoucluMQqkB0o%3D
The same Java code would be:
public static void main(String args[]) {
String data = "The fault dear Brutus lies not in our stars";
String key = "d134hjeefcgkahvg32ajkdbaff84ff180";
String out = null;
try {
out = calcMAC(data, key.getBytes());
System.out.println(URLEncoder.encode(out, "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
}
Again, we can put anything into 'data' we want.
I am doing Tableau integration with web project using java script api. I have configured my ip in tableau server using commnad :tabadmin set wgserver.trusted_hosts "" and respective commands .But I am not able to get the ticket, ended up with -1. I have followed all configuration steps.
public class TableauServlet extends javax.servlet.http.HttpServlet {
private static final long serialVersionUID = 1L;
public TableauServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
final String user = "raghu";
final String wgserver = "103.xxx.xxx.xx";
final String dst = "views/Regional/College?:iid=1";
final String params = ":embed=yes&:toolbar=yes";
String ticket = getTrustedTicket(wgserver, user, request.getRemoteAddr());
if ( !ticket.equals("-1") ) {
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location", "http://" + wgserver + "/trusted/" + ticket + "/" + dst + "?" + params);
}
else
// handle error
throw new ServletException("Invalid ticket " + ticket);
}
// the client_ip parameter isn't necessary to send in the POST unless you have
// wgserver.extended_trusted_ip_checking enabled (it's disabled by default)
private String getTrustedTicket(String wgserver, String user, String remoteAddr)
throws ServletException
{
OutputStreamWriter out = null;
BufferedReader in = null;
try {
// Encode the parameters
StringBuffer data = new StringBuffer();
data.append(URLEncoder.encode("username", "UTF-8"));
data.append("=");
data.append(URLEncoder.encode(user, "UTF-8"));
data.append("&");
data.append(URLEncoder.encode("client_ip", "UTF-8"));
data.append("=");
data.append(URLEncoder.encode(remoteAddr, "UTF-8"));
// Send the request
URL url = new URL("http://" + wgserver + "/trusted");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
out = new OutputStreamWriter(conn.getOutputStream());
out.write(data.toString());
out.flush();
// Read the response
StringBuffer rsp = new StringBuffer();
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ( (line = in.readLine()) != null) {
rsp.append(line);
}
return rsp.toString();
} catch (Exception e) {
throw new ServletException(e);
}
finally {
try {
if (in != null) in.close();
if (out != null) out.close();
}
catch (IOException e) {}
}
}
}
I think you are missing 'target_site' parameter in your URL where you get trusted ticket, its needed if you don't have the 'views/Regional/College' in your default site.
I had gone through a lot of frustration with the '-1' ticket too!
One thing you might try is restarting the tableau server after you have added your web server IP to the trusted_hosts of tableau.
Another thing we ended up doing was adding both the internal ip and external ip of the web server to trusted_hosts on tableau. Since you are using 103.xxx.xxx.xx as your tableau server I am assuming both servers live on the same internal network. You might try that if everything else fails.
My code is almost exactly same as yours and works fine. So if your problem persists, it must be something related to configuration.
here is my code:
private String getAuthenticationTicket(String tableauServerUserName,String tableauServerUrl, String targetSite) {
OutputStreamWriter out = null;
BufferedReader in = null;
try {
StringBuffer data = new StringBuffer();
data.append(URLEncoder.encode("username", Constant.UTF_8));
data.append("=");
data.append(URLEncoder.encode(tableauServerUserName, Constant.UTF_8));
data.append("&");
data.append(URLEncoder.encode("target_site", Constant.UTF_8));
data.append("=");
data.append(URLEncoder.encode(targetSite, Constant.UTF_8));
URL url = new URL(tableauServerUrl + "/" + "trusted");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
out = new OutputStreamWriter(conn.getOutputStream());
out.write(data.toString());
out.flush();
StringBuffer rsp = new StringBuffer();
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
rsp.append(line);
}
return rsp.toString();
} catch (Exception ex) {
//log stuff, handle error
return null;
} finally {
try {
if (in != null)
in.close();
if (out != null)
out.close();
} catch (IOException ex) {
//log stuff, handle error
}
}
}
I'm new to Java and Android development and try to create a simple app which should contact a web server A and send,add some data to text using a http get.
I have simple HTML code with some javascript (server A)
<html>
<head>
<title>This is my Webpage</title>`enter code here`
<h1>My Example</h1>
<script>
function myFunction(){
document.getElementById("myid").value=$ab;
}
</script
</head>
<body onload="myFunction()">
<input id="myid" type="text" />
</body>
</html>
and i have Android code to send http request to a local (server A)
public class MainActivity extends Activity {
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button) findViewById(R.id.click);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = "http://www.localhost/tuan/example.html";
MyCommandTask task = new MyCommandTask();
task.execute(url);
}
});
}
public class MyCommandTask extends AsyncTask<String,Void,Document>
{
#Override
protected Document doInBackground(String... params) {
String url=params[0];
try {
HttpGet httpGet = new HttpGet(url);
}
catch (Exception ex)
{
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Document document) {
super.onPostExecute(document);
}
}
}``
Now i want send text data and show result in text on (server A).
Please anyone help me.
Check this out dude. http://developer.android.com/training/basics/network-ops/connecting.html#download . Since you already got url string in doInBackground() method , use below code
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
Don't forget to change return type of doInBackground() to String as well. If you wanna go further , try grab volley which is one of the awesome network library https://developer.android.com/training/volley/index.html
Here is how you can post data to server. Put these line inside doInBackground()
private static final String POST_PARAMS = "userName=Pankaj";
URL obj = new URL(POST_URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} else {
System.out.println("POST request not worked");
}
Here is the source
I am currently a beginner to android programming and right now I am developing an app to make a JSON connection to a LAMP server and display the JSON data. The connection is currently successfully being made and i can create product and see it in the db but the app unexpectedly close's every time, can someone help and point me in the right direction, will add more if needed.
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) {
is = null;
jObj = null;
json = "";
// Making HTTP request
try {
Log.i("url", url);
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
Log.i("url", url);
HttpPost httpPost = new HttpPost(url);
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;
Log.i("url", url);
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();
}
Log.i("Stage 1", "Stage 1");
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");
Log.i("1 ", line);
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
Log.i("Stage 2", "Stage 2");
// 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());
}
Log.i("Stage 3", "Stage 3");
// return JSON String
return jObj;
}
public class NewProductActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputDesc;
// url to create new product
private static String url_create_product = "http://192.168.1.165/wp-admin/android_connect/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);
// Edit Text
inputName = (EditText) findViewById(R.id.inputName);
inputPrice = (EditText) findViewById(R.id.inputPrice);
inputDesc = (EditText) findViewById(R.id.inputDesc);
// Create button
Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
#SuppressWarnings("ResourceType")
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String price = inputPrice.getText().toString();
String description = inputDesc.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("description", description));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
logcat 09-16 10:47:27.285
23440-23458/com.example.androidhive.productjsonphp I/OpenGLRenderer﹕
Initialized EGL, version 1.4 09-16 10:47:27.287
23440-23458/com.example.androidhive.productjsonphp D/OpenGLRenderer﹕
Enabling debug mode 0 09-16 10:47:28.372
23440-23440/com.example.androidhive.productjsonphp V/Monotype﹕
SetAppTypeFace- try to flip, app =
com.example.androidhive.productjsonphp 09-16 10:47:28.372
23440-23440/com.example.androidhive.productjsonphp V/Monotype﹕
Typeface getFontPathFlipFont - systemFont = default#default 09-16
10:47:28.449 23440-23471/com.example.androidhive.productjsonphp
I/url﹕
http://api.androidhive.info/android_connect/get_all_products.php 09-16
10:47:28.451 23440-23471/com.example.androidhive.productjsonphp
I/url﹕
http://api.androidhive.info/android_connect/get_all_products.php?
09-16 10:47:28.674 23440-23458/com.example.androidhive.productjsonphp
D/OpenGLRenderer﹕ endAllStagingAnimators on 0xb7f62f50
(RippleDrawable) with handle 0xb7f75e00 09-16 10:47:29.017
23440-23471/com.example.androidhive.productjsonphp I/Stage 1﹕ Stage 1
09-16 10:47:29.022 23440-23471/com.example.androidhive.productjsonphp
I/1﹕ Unknown database 'download_androidhive' 09-16 10:47:29.022
23440-23471/com.example.androidhive.productjsonphp I/Stage 2﹕ Stage 2
09-16 10:47:29.023 23440-23471/com.example.androidhive.productjsonphp
E/JSON Parser﹕ Error parsing data org.json.JSONException: Value
Unknown of type java.lang.String cannot be converted to JSONObject
09-16 10:47:29.023 23440-23471/com.example.androidhive.productjsonphp
I/Stage 3﹕ Stage 3 09-16 10:47:29.029
23440-23471/com.example.androidhive.productjsonphp E/AndroidRuntime﹕
FATAL EXCEPTION: AsyncTask #1
Process: com.example.androidhive.productjsonphp, PID: 23440
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a
null object reference
at com.example.androidhive.productjsonphp.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:130)
at com.example.androidhive.productjsonphp.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:105)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818) 09-16 10:47:29.528 23440-23440/com.example.androidhive.productjsonphp
E/WindowManager﹕ android.view.WindowLeaked: Activity
com.example.androidhive.productjsonphp.AllProductsActivity has leaked
window com.android.internal.policy.impl.PhoneWindow$DecorView{78d7c4f
V.E..... R......D 0,0-479,116} that was originally added here
at android.view.ViewRootImpl.(ViewRootImpl.java:363)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:298)
at com.example.androidhive.productjsonphp.AllProductsActivity$LoadAllProducts.onPreExecute(AllProductsActivity.java:117)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.example.androidhive.productjsonphp.AllProductsActivity.onCreate(AllProductsActivity.java:57)
at android.app.Activity.performCreate(Activity.java:5975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2378)
at android.app.ActivityThread.access$800(ActivityThread.java:147)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5255)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:838)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:651) 09-16
10:47:34.521 23440-23471/com.example.androidhive.productjsonphp
I/Process﹕ Sending signal. PID: 23440 SIG: 9
Your try to parse Json from String "json" but this "json" string give null value, if Please check "json" string is null, before use it.
so, try this code
if(json!=null && !json.equals(""))
{
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
)else{
Toast.makeText(context, "json is empty", Toast.LENGTH_LONG).show();
}