0

I am very sorry for this questions, but I am a new on Android and Android Studio. I want to send a request to an api and I want the result of the query. I have never send an HTTP request, I have searched on google I have saw to do something like this:

public class HttpClient {
private static final String TAG = "HttpClient";

public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {

    try {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPostRequest = new HttpPost(URL);

        StringEntity se;
        se = new StringEntity(jsonObjSend.toString());

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json");
        httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression

        long t = System.currentTimeMillis();
        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
        Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");

        // Get hold of the response entity (-> the data):
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            // Read the content stream
            InputStream instream = entity.getContent();
            Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                instream = new GZIPInputStream(instream);
            }

            // convert content stream to a String
            String resultString= convertStreamToString(instream);
            instream.close();
            resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"

            // Transform the String into a JSONObject
            JSONObject jsonObjRecv = new JSONObject(resultString);
            // Raw DEBUG output of our received JSON object:
            Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");

            return jsonObjRecv;
        } 

    }
    catch (Exception e)
    {
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    }
    return null;
}


private static String convertStreamToString(InputStream is) {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     * 
     * (c) public domain: http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple-restful-client-at-android/
     */
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

}

In my other activity I have set the private static final String URL = myurl; (it is an example). I think that It is the right way, but I am really not sure of what I am doing... The other problem is when I tried to execute the HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest); I have this error: Android - android.os.NetworkOnMainThreadException I think the problem is that I don't know how to import

org.apache.http.Header;
import org.apache.http.HttpEntity;

etc.. How to import them on my project? I have already set <uses-permission android:name="android.permission.INTERNET"></uses-permission> on my AndroidManifest.

Thank you.

EDIT(RESOLVED): On the 23.0.0 Gradle version, the apache package doesn't work because It is deprecated, If i try to downgrade my grandle version I had problem with the layout etc. The solution that I have find is to use Volley jar and method.

Liz Lamperouge
  • 681
  • 14
  • 38
  • `android.os.NetworkOnMainThreadException` occurs when you are executing a `Network Call` on main thread. You should use `Handler` or `AsyncTask` instead – Satyen Udeshi Sep 16 '15 at 07:27

1 Answers1

0

This code is properlyworkingin my project to sendjson data to server and accept the response.

public static final String url ="your url";

after this all your code here i.e json or something 

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("allData",jarray.toString()));
    String resultServer  = getHttpPost(url,params); // Here to pass the url and parameter as student data

// getHttpPost method

    private String getHttpPost(String url, List<NameValuePair> params) 
    {

        // TODO Auto-generated method stub

             sb = new StringBuilder();
             HttpClient client = new DefaultHttpClient();
             HttpPost httpPost = new HttpPost(url);
            //  Log.d("Entire httppost::", " " + httpPost);
             //httpPost.setHeader("Accept", "application/json");
              //  httpPost.setHeader("Content-type", "application/json");
             try {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                    HttpResponse response = client.execute(httpPost); // get the response from same url
                    HttpEntity entity = response.getEntity();         // set the response into HttpEntity Object
                    is = entity.getContent();                         // Assign the response content to inputStream Object 
                    Log.e("server Response", "json format "+is);


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

             if(is!=null )
             {
             try{   //this try block is for to handlethe response inputstream
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                    sb = new StringBuilder();
                    sb.append(reader.readLine() + "\n");
                    String line="0";

                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }

                    is.close();
                    result=sb.toString();
                    Log.d("RESULT inside try block(sb) ", " " + result);
                }catch(Exception e){
                    Log.e("log_tag", "Error converting result "+e.toString());
                }

return sb.toString();
         }  

}
Asmi
  • 365
  • 6
  • 21
  • How you have import new DefaultHttpClient();? – Liz Lamperouge Sep 16 '15 at 07:38
  • import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; – Asmi Sep 16 '15 at 07:41
  • This all imports are auto import when I wrote above code – Asmi Sep 16 '15 at 07:41
  • And its working properly.. – Asmi Sep 16 '15 at 07:42
  • Cannot resolve symbol "HttpEntity", you have import jar dependecies or something like that? – – Liz Lamperouge Sep 16 '15 at 08:30
  • yes I used android-async-http-1.4.4.jar in lib folder – Asmi Sep 16 '15 at 08:38
  • I import the jar but It doens't work....I have the same error Cannot resolve symbol "HttpEntity".... And if I try to debug I have this error : "Error:(15, 23) error: package org.apache.http does not exist" and Error:(29, 13) error: cannot find symbol class DefaultHttpClient.... and other... – Liz Lamperouge Sep 16 '15 at 09:02
  • @LizLamperouge Sometimes after importing external libraries, I have to refresh dependencies or close and open the project to get the eclipse errors to go away. Do clean project. Select project option-> Select clean and clean the project – Asmi Sep 16 '15 at 09:05
  • I have already clean the project, I am using Android Studio, now I will try to close and re-open android studio – Liz Lamperouge Sep 16 '15 at 09:08
  • http://stackoverflow.com/a/31552681/5069663 See this. Even I used thread to run my service. – Asmi Sep 16 '15 at 09:18
  • @LizLamperouge The reason is because you didn't use Async Task to carry out the network process. Please use Async task to make sure your app runs without error. Still if you don't want to use Async task, please add the following code StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); This solution just hides your problem. Behavious may be expected. Its better to go with async task – Asmi Sep 16 '15 at 13:13
  • if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } – Asmi Sep 16 '15 at 13:16
  • I have understand what are my problem. First of all, I have the 23 grandle version so I can't use android-async-http-1.4.4.jar, because I have to downgrade my grandle version and android api level, if I downgrade the grandle/android version I have other error... Now i am trying to download org.apache.http.legacy.jar but I for now I haven't found it. – Liz Lamperouge Sep 16 '15 at 13:23