0

As HttpClient was deprecated in API Level 22 and removed in API Level 23, I used

android {
    useLibrary 'org.apache.http.legacy'
}

and

compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'` 

according to this link : Lik1 and Link 2 . I used below class to connect and read information from server:

public class Webservice {

public static String readurl(String url, ArrayList<NameValuePair> params) {

    try {
        HttpClient client = new DefaultHttpClient();
        HttpPost method = new HttpPost(url);
        if (params != null) {
            method.setEntity(new UrlEncodedFormEntity(params));

        }
        HttpResponse response = client.execute(method);
        InputStream stream = response.getEntity().getContent();
        String result = inputstreamTOString(stream);
        return result;
    }
    catch (ClientProtocolException e) {

        e.printStackTrace();
    }
    catch (IOException e) {

        e.printStackTrace();
    }

    return null;
}
}

but when i run my app, it has crashed in String result = Webservice.readurl(url, params); in below cod:

public void populateFromServer() {

    String url = G.server_service;
    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("action", "read"));
    String result = Webservice.readurl(url, params);

.
.
.
}
Community
  • 1
  • 1
hasti
  • 3
  • 2

1 Answers1

0

Since you didn't specify what exactly was the error. I'll give you a beautiful code for HttpTask that works great with JSONParser.

This code will work if your middleware responds with a JSON.

To call HTTPTask

Boolean Some_variable = new HttpTask(getBaseContext()).doInBackground("test");

HttpTask

package com.example.summer.toothbrush;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

public class HttpTask extends AsyncTask<String,Void,Boolean> {

    Context mainContext;
    JSONObject jsonObject;

    public HttpTask(Context context){ mainContext = context;  }

    @Override
    protected Boolean doInBackground(String... params){
    jsonObject = new JSONObject();
    JSONObject responseJsonObject = new JSONObject();
    StringBuilder result = new StringBuilder("");
    JSONParser jsonParser = new JSONParser(mainContext);
    if(params[0] == "test")
        jsonObject.put("test", "test");

    try{
        responseJsonObject = jsonParser.passJSONinURL(jsonObject,params[0]);
        result.append(responseJsonObject.get("status").toString());
        Log.d("Result", result.toString());
    }
    catch(JSONException e){
        e.printStackTrace();
    }
    if(result.toString().equals("true"))
        return true;
    else
        return false;
    }
}

JSONParser

package com.example.summer.toothbrush;

import android.content.Context;
import android.os.StrictMode;
import android.util.Log;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;

public class JSONParser {

Context mainContext;
HttpResponse response;
StringBuilder result = new StringBuilder("");

public JSONParser(Context context){
    mainContext = context;
}

public JSONObject passJSONinURL(JSONObject obj,String mode){
    StringBuilder builder = new StringBuilder("");
    JSONObject jsonObject = new JSONObject();

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    try{
        response = null;
        HttpClient httpClient = new DefaultHttpClient();
        StringBuilder stringURL = new StringBuilder("");
        stringURL.append("http://100.100.10.10:8000/");
        if(mode.equals("test"))
            stringURL.append("test");

        //URLEncoder.encode() is used to encode the parameters in a request.
        stringURL.append(URLEncoder.encode(obj.toString(),"UTF-8"));
        //Toast.makeText(mainContext, stringURL.toString(),Toast.LENGTH_LONG).show();
        Log.d("JSON to be sent",stringURL.toString());
        HttpGet get = new HttpGet(stringURL.toString());
        response = httpClient.execute(get);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if(statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            reader.close();
        }
        else{
            Toast.makeText(mainContext,"Status Code Error!!!",Toast.LENGTH_LONG).show();
        }

    }
    catch(ClientProtocolException e){
        e.printStackTrace();
    }
    catch(IOException e){
        e.printStackTrace();
    }

    try{
        jsonObject = new JSONObject(builder.toString());

    }catch(JSONException e){
        Toast.makeText(mainContext,"JSON Parsing ERROR!!!!",Toast.LENGTH_LONG).show();
    }
    Log.d("JSONOBJECT : ",jsonObject.toString());
    return jsonObject;
}
}
rv.
  • 81
  • 1
  • 2
  • 8