postexecute in asynctask is not executing - android

#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
url3="http://www.digitalmarketingbox.com/webtool/boxdata/"+MainActivity.abc+"/updates.zip";
try {
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
// HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con =(HttpURLConnection) new URL(params[0]).openConnection();
con.setRequestMethod("HEAD");
x=con.getResponseCode() == HttpURLConnection.HTTP_OK;
}
catch (Exception e) {
e.printStackTrace();
x=false;
}
try {
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
// HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con =(HttpURLConnection) new URL(url3).openConnection();
con.setRequestMethod("HEAD");
xc=con.getResponseCode() == HttpURLConnection.HTTP_OK;
}
catch (Exception e) {
e.printStackTrace();
xc=false;
}
//x=exists(params[0]);
//xc=exists(url3);
valve=String.valueOf(x);
if(valve.equals("true"))
{
finalurl=url+ MainActivity.abc + "/resources.zip";
filename="resources.zip";
MainActivity.fl1=filename;
Log.i("filename",filename);
}
else if(xc==true)
{
finalurl=url+ MainActivity.abc + "/updates.zip";
filename="updates.zip";
MainActivity.fl1=filename;
Log.i("filename",filename);
}
else
{
try
{
HttpClient client = new DefaultHttpClient();
Log.i("url for checking update",url1);
HttpPost post = new HttpPost(url1);
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("reqtype", "resendcontent"));
parameters.add(new BasicNameValuePair("menuboxid",MainActivity.abc));
parameters.add(new BasicNameValuePair("updatetoken", "dmb20101512"));
UrlEncodedFormEntity ent;
ent = new UrlEncodedFormEntity(parameters,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
finalurl=url+ MainActivity.abc + "/updates.zip";
filename="updates.zip";
MainActivity.fl1=filename;
Log.i("filename",filename);
Log.i("url",finalurl);
}
catch (final IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finalurl=url+ MainActivity.abc + "/updates.zip";
filename="updates.zip";
MainActivity.fl1=filename;
}
try{
URL url = new URL(finalurl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
//File SDCardRoot = Environment.getExternalStorageDirectory();
filedestination=Environment.getExternalStorageDirectory() +"/" + filename;
//File file = new File(SDCardRoot,filename);
File file = new File(filedestination);
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
totalSize = urlConnection.getContentLength();
Log.i("size",String.valueOf(totalSize));
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
}
//close the output stream when complete //
fileOutput.close();
}
catch (final IOException e) {
e.printStackTrace();
}
Log.i("download info","Download complete");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String source = Environment.getExternalStorageDirectory() + "/" + filename;
Log.i("Download destination",source);
String destination =Environment.getExternalStorageDirectory()+ "/";
Log.i("Extract destination",destination);
try {
ZipFile zipFile = new ZipFile(source);
zipFile.extractAll(destination);
} catch (ZipException e) {
e.printStackTrace();
}
try
{
HttpClient client1 = new DefaultHttpClient();
Log.i("url is",url1);
HttpPost post1 = new HttpPost(url1);
List<NameValuePair> parameters1 = new ArrayList<NameValuePair>();
parameters1.add(new BasicNameValuePair("reqtype", "completeupdate"));
parameters1.add(new BasicNameValuePair("menuboxid",MainActivity.abc));
parameters1.add(new BasicNameValuePair("updatetoken", "dmb20101512"));
UrlEncodedFormEntity ent1 = new UrlEncodedFormEntity(parameters1,HTTP.UTF_8);
post1.setEntity(ent1);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return foo;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stu
super.onPostExecute(result);
//result=bn;
/*if(!result.isEmpty())
{
Calendar c = Calendar.getInstance();
int seconds = c.get(Calendar.SECOND);
Log.i("AsyncTask finish time",String.valueOf(seconds));
}*/
}
i am using this asynctask class in my activity to do some task and checking via the getstatus method that it has finished or not ,but it is never finished
above is my code of my asynctask class and its postexecute is not working can someone expalin me why?

I have also experienced the same problem. It happens when your Main UI thread goes to sleep. Try to use a timer in your UI thread to keep it awake.

Related

Android App Crashes if no internet during server connection

I am calling a url to fetch data and insert in my database. I have provided a no internet check. If I open the app without internet connection, it works fins, a pop up comes.. But if I connect to the url when I have internet and the internet goes in middle the process, my app crashes, How to fix it?
My code:
public class DoPOSTPen extends AsyncTask<String, Void, Boolean> implements OnCancelListener {
#SuppressWarnings("deprecation")
#Override
protected Boolean doInBackground(String... arg0) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://testapi.pharmeazy.in/api/MediEazy/GetAllInvoices");
request.addHeader("Authorization", " basic NDlyaWNva2pvaWQwM2ptZGlraWRES09qZGZpamRmNzY0dDA4NWp6MzcyOHdzMkpJS1M4MTA0c2NvcTJ1OTRkazphd0VEMzI3MkA4WWFzZEU3MjI3IUBeIypVSFMq");
request.setHeader(HTTP.CONTENT_TYPE, "application/json");
System.out.println("PRIINTING");
HttpResponse response = null;
try {
response = client.execute(request);
Log.d("Response of GET request", response.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream inputStream = response.getEntity().getContent();
String result = Utils.convertInputStreamToString(inputStream);
System.out.println("server response is :" + result + "\n" + inputStream);
try {
ja=new JSONArray(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (Exception e) {
Log.e("ClientServerDemo", "Error:", e);
toastText2 = "Connection Error !";
}
return true;
}
protected void onPreExecute() {
//display the progress dialog
mProgressHUD2 = ProgressHUD.show(Med.this,"Getting Rejected Orders", true,false,this);
}
#Override
protected void onPostExecute(Boolean valid) {
mProgressHUD2.dismiss();
// if server response is successful
for(int i=0;i<ja.length();i++){
try {
jo=ja.getJSONObject(i);
db.insertLabel(jo.get("Id").toString(), jo.get("CustomerId").toString(), jo.get("PharmacyId").toString(),
jo.get("DeliveryAddress").toString(), jo.get("DeliveryName").toString(),
jo.get("OrderStatus").toString(),jo.get("PrescriptionAttached").toString(),jo.get("Discount").toString());
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
new DoPOST3().execute();
}
Please help
why you don't go for httpurlconection
#Override
protected String doInBackground(String... params) {
String finalResult = null;
URL url = null;
HttpsURLConnection urlConnection = null;
try {
url=new URL(URL);
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
urlConnection.setRequestProperty("Content-Type","application/json");
urlConnection.connect();
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(jsonObjSend.toString());
out.close();
starttime = System.currentTimeMillis();
try {
mResponseCode = urlConnection.getResponseCode();
totaltime = System.currentTimeMillis() - starttime;
Log.e("HTTP POST Response Code:", ""
+ mResponseCode);
} catch (SSLPeerUnverifiedException e) {
Log.e("Exception", Log.getStackTraceString(e));
} catch (IOException e) {
Log.e("Exception", Log.getStackTraceString(e));
Log.e("HTTP POST Response Code(2):", ""
+ mResponseCode);
}
}
check before calling asynctask
if(Util.haveNetworkConnection(this))
{
HttpPostData req=new HttpPostData(URL, createJsonObject(),this) ;
req.execute();
}

install video in local memory and play in there in android

how can I install video from url in local memory and play in there in android? Can you share example code about this? I tried like below but I get error "Sorr,this video cannot played" Video cannot played,but code is installing to video file .I can see it "File Explorer"
public class VideoSaveSDCARD extends Activity {
private VideoView vView;
private static final String TAG = "UpdaterService";
File SDCardRoot;
Handler asyncHandler = new Handler();
String videoLink = "http://hurriyettv.cubecdn.net/2014/11/19/htv_99710_240p.mp4";
String name = "blaa.mp4";
private Updater updater;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
SDCardRoot = new File(getFilesDir() + "/videos");
File[] videos = SDCardRoot.listFiles();
vView = (VideoView) findViewById(R.id.vview);
try {
String[] fileArray = new String[videos.length];
for (int i = 1; i < 2; i++) {
fileArray[i] = videos[i].getName();
Log.i("#Tag:file[1]", "" + fileArray[i]);
vView.requestFocus();
vView.setVideoPath("" + fileArray[i]);
vView.start();
// MediaPlayer pl = new MediaPlayer();
// pl.setDataSource(fi.getFD());
// pl.prepare();
// pl.start();
//
}
} catch (Exception e) {
// TODO: handle exception
}
/*
* Log.i("fileeee", "" + videos[1]);
*
* vView = (VideoView) findViewById(R.id.vview);
*
* // use this to get touch events vView.requestFocus();
*
* // load video from SD card vView.setVideoPath(
* "/data/data/com.example.downlaodvideo/files/videos/blaa.mp4");
*
* // enable this if you want to enable video controllers, such as pause
* // and forward
*
* // plays the movie vView.start();
*/
File SDCardRoot = new File(VideoSaveSDCARD.this.getFilesDir() + "/"
+ "videos");
if (!SDCardRoot.exists()) {
SDCardRoot.mkdir();
}
// deleteDirectory(SDCardRoot);
updater = new Updater();
updater.start();
}
class Updater extends Thread {
#Override
public void run() {
super.run();
downloadFiles(videoLink, name);
}
}
synchronized boolean downloadFiles(String link, String videoName) {
try {
URL url = new URL(link); // you can write here any link
long startTime = System.currentTimeMillis();
Log.d("VideoManager", "download begining");
Log.d("VideoManager", "download url:" + url);
Log.d("VideoManager", "downloaded file name:" + videoName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(new File(SDCardRoot,
videoName));
fos.write(baf.toByteArray());
fos.close();
Log.d("VideoManager",
"download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
return true;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
public String getDataFromPortal(String remoteUrl, String myString) {
String data = null;
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(remoteUrl + myString);
try {
HttpResponse response1 = httpclient.execute(httpGet);
InputStream is = response1.getEntity().getContent();
data = getStringFromInputStream(is);
return data;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
Log.d(TAG, "................internet yok catch 1");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d(TAG, "................internet yok catch 2");
e.printStackTrace();
}
// The underlying HTTP connection is still held by the response
// object
// to allow the response content to be streamed directly from the
// network socket.
// In order to ensure correct deallocation of system resources
// the user MUST either fully consume the response content or abort
// request
// execution by calling HttpGet#releaseConnection().
return data;
}
private String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
public static boolean deleteDirectory(File path) {
if (path.exists()) {
File[] files = path.listFiles();
if (files == null) {
return true;
}
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteDirectory(files[i]);
} else {
files[i].delete();
}
}
}
return (path.delete());
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("on create","on create");
setContentView(R.layout.activity_main);
new Asyntask().execute();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
SDCardRoot = new File("/sdcard/videos");
Log.d("SDCARDGGHGHg",""+SDCardRoot);
File[] videos = SDCardRoot.listFiles();
//Log.d("Videos array ",""+videos[0].getName());
vView = (VideoView) findViewById(R.id.vview);
Log.d("before try cathc","testing");
File SDCardRoot = new File("/sdcard/videos");
Log.d("SDCardRoot",""+SDCardRoot);
if (!SDCardRoot.exists()) {
SDCardRoot.mkdir();
}
}
class Asyntask extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
Log.d("In background","in background");
URL url;
try {
url = new URL(videoLink);
long startTime = System.currentTimeMillis();
Log.d("VideoManager", "download begining");
Log.d("VideoManager", "download url:" + url);
Log.d("VideoManager", "downloaded file name:" + name);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos;
fos = new FileOutputStream(new File(SDCardRoot,
name));
fos.write(baf.toByteArray());
fos.close();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (Exception e) {
// TODO: handle exception
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
Log.d("In post","in post");
vView.setVideoPath(SDCardRoot+"/blaa.mp4");
vView.start();
Log.d("android","post execute");
super.onPostExecute(result);
}
}
This will run your code.

unable to save data to txt in loop asynctask

I am trying to save every output data in asynctask for each http call.But I am unable to see any data in a file.I really appreciate any help.Thanks in Advance.
final String[] ar={"1","2","3",.............,"25"}
filename="test_file";
myFile = new File("/sdcard/"+filename);
try {
myFile.createNewFile();
fOut = new FileOutputStream(myFile);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
myOutWriter = new OutputStreamWriter(fOut);
for ( j = 0; j < ar.length; j++) {
u="http://www.example.com/"+ar[j];
JSONParser jParser=new JSONParser();
new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,u);
}
try {
myOutWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class MyAsyncTask extends AsyncTask<String, String, Void> {
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream inputStream = null;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Downloading your data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
MyAsyncTask.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... params) {
String url_select = params[0];
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet(url_select));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
//
// // Read content & Log
// inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncodingException", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
}
return null;
} // protected Void doInBackground(String... params)
protected void onPostExecute(Void v) {
//parse JSON data
try{
JSONObject jArray = new JSONObject(result);
String name = jArray.getString("name");
if (name!=null) {
Log.w("idname", name);
//
myOutWriter.append(name).append("\r\n");
//
Toast.makeText(getBaseContext(), name, 5).show();
}
// End Loop
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // protected void onPostExecute(Void v)
} //class MyAsyncTask extends AsyncTask<String, String, Void>
for ( j = 0; j < ar.length; j++) {
u="http://www.example.com/"+ar[j];
JSONParser jParser=new JSONParser();
new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,u);
}
try {
myOutWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You close the myOutWriter after start MyAsyncTask. So when MyAsyncTask try to write data to file, it throw OutputStreamWriter is closed exception.
You need remove the code of close myOutWriter from here. Add add close code at the end of onPostExecute like below:
void onPostExecute(Void v) {
.....
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int count = taskCount.decrementAndGet()
if(count == 0 ) {
try {
myOutWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} // protected void onPostExecute(Void v)
the definition of taskCount is like this:
AtomicInteger taskCount = new AtomicInteger(ar.length - 1);
At last, I think Thread and CountDownLatch is better option
check if entity not null then write to db
HttpEntity entity = response.getEntity();
if(entity!=null ){
inputStream = entity.getContent();
}

Android gcm sending link testing

Sir,,
I would like to try my application to test push-notification by typing this link below , but it comes to trying , there is no effect.Would you please tell me what is the correct format for the hyperlink to test my Application program ?
The below is my link
https://android.googleapis.com/gcm/send?registration_ids=
APA91bHhJQJGK1OJxYHcZeH81JoAprU97CAvMHQ58cHj3MYHD204MTn1W9Kl_i51UV8ej5qwLfkwvK-vihfuWjXG6iBvkUZJuclqoNbAjx_K2mN_P2ai4rI82P0dax_tm7NHc-k_1FsBn6hvwxjxxPdgMdtYpSIdwA
&data.message="hello testing"
collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "
You can actually test it from the Android device itself:
public class PushTester {
final static private String deviceId = "YOUR_DEVICE_ID";
final static private String apiId = "YOUR_API_ID";
final static private String sendUrl = "https://android.googleapis.com/gcm/send";
static void testPush() {
URL url;
HttpsURLConnection urlConnection;
OutputStream os = null;
InputStream is = null;;
try {
url = new URL(sendUrl);
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(3000);
urlConnection.setReadTimeout(3000);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("User-Agent", "Android Push tester");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Authorization", "key="+apiId);
JSONObject message = new JSONObject();
JSONArray regIds = new JSONArray();
JSONObject data = new JSONObject();
regIds.put(deviceId);
message.put("registration_ids", regIds);
//message.put("collapse_key", value)
data.put("something", "value");
message.put("data", data);
urlConnection.setDoOutput(true);
os = urlConnection.getOutputStream();
os.write(message.toString().getBytes());
os.flush();
int status = urlConnection.getResponseCode();
is = urlConnection.getInputStream();
byte[] response = new byte[4096];
is.read(response);
String responseText = String.valueOf(response);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
if (os != null) {
os.close();
}
if (is != null) {
is.close();
}
}
catch (Exception ex) {
ex.printStackTrace();
}
os = null;
is = null;
}
}
}

how to post using HttpUrlConnection in android -> getting error : java.io.IOException: content-length promised 82 bytes, but received 43

Hello here I am trying for the post data from android to server.I am trying using HttpURLConnection.
Here I am sending username & password for Authentication for entering data for particular user in drupal. I have also tried to post data with various other methods. Using DefaultHttpClient but no luck. I am getting 401 error with using DefaultHttpClient.
Here is the link of question that I have asked on stackoverflow. Authentication error: Unable to respond to any of these challenges: {} Android - 401 Unauthorized
SO please help. Thanks for listening.
Here is my code.
public static class post_idea extends AsyncTask<Void, Void, Void> {
String strResponse1;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pgb.setVisibility(View.VISIBLE);
}
#Override
public Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// String url = "http://testingd7.mobileapplicationtesters.com/my_android_drupal/user/login";
String url = "http://testingd7.mobileapplicationtesters.com/my_android_drupal/node.json";
// String url = "http://mobiappdevelopers.com/drupal_test/my_android_drupal/node.json";
//String url = "http://www.drupal7.mobileapplicationtesters.com/my_services/node.json";
strResponse1 = makeWebForPostIdea(url,title,body);
System.out.println("=========> Response from post idea => "
+ strResponse1);
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pgb.setVisibility(View.GONE);
}
public static String makeWebForPostIdea(String url123, String title,String body)
{
HttpURLConnection httpcon = null;
JSONObject json = null;
JSONObject jsonnode = null;
try {
JSONObject jsonvalue = new JSONObject();
jsonvalue.put("value", body.toString());
JSONArray array = new JSONArray();
array.put(jsonvalue);
jsonnode = new JSONObject();
jsonnode.put("und", array);
System.out.println("######2 jsonnode=======>"+jsonnode.toString());
json = new JSONObject();
json.put("title",title);
json.put("body", jsonnode);
json.put("type","article");
System.out.println("value of the combine node=======>"+json.toString());
} catch (JSONException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
try {
httpcon = (HttpURLConnection) ((new URL(url123).openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
String urlParameters =
"type=" + URLEncoder.encode("page", "UTF-8") +
"title=" + URLEncoder.encode(title, "UTF-8") +
"body" + URLEncoder.encode(jsonnode.toString(), "UTF-8") ;
httpcon.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
httpcon.connect();
byte[] outputBytes = "{\"username\":\"uname\",\"password\":\"pass\"}".getBytes("UTF-8");
OutputStream os = httpcon.getOutputStream();
os.write(outputBytes);
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
Thanks.
You set the content length here:
httpcon.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
But the content you sent comes from here:
byte[] outputBytes = "{\"username\":\"uname\",\"password\":\"pass\"}".getBytes("UTF-8");
OutputStream os = httpcon.getOutputStream();
os.write(outputBytes);
So the reported Content-Length does not match the actual content length.
Ignore the httpcon.connect(); in the middle, it does nothing because you are already connected.
Instead, you need to do:
byte[] outputBytes = "{\"username\":\"uname\",\"password\":\"pass\"}".getBytes("UTF-8");
httpcon.setRequestProperty("Content-Length", Integer.toString(outputBytes.length()));
OutputStream os = httpcon.getOutputStream();
os.write(outputBytes);

Categories

Resources