Android Http Get Request

2019-09-15 15:26发布

问题:

I'm a newbie at android development. I'm trying to send a GET request to an URL. I wrote the below code.

public void searchProducts(View v) 
{
    //String txtSearchTerm = ((EditText)findViewById(R.id.txtsearch)).getText().toString();
    //String termCleaned = txtSearchTerm.replace(' ', '+').toString();
    AlertDialog alertMessage = new AlertDialog.Builder(this).create();
    alertMessage.setTitle("Loading");
    alertMessage.setMessage(GET("http://webkarinca.com/sample.json"));
    alertMessage.show(); 
} 
public static String GET(String url){
    InputStream inputStream = null;
    String result = "";
    try {

        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
        inputStream = httpResponse.getEntity().getContent();
        if(inputStream != null)
        {
            result = convertInputStreamToString(inputStream);
        }
        else
        {
            result = "Did not work!";
        }

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;

}

I already put imports head of the class. There they are

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

It doesn't work and at the Problems section it shows as a warning

The type HttpGet is deprecated The type HttpResponse is deprecated

回答1:

try this

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;

import android.content.Context;

import com.jivebird.settings.CommonMethods;

public class Connecttoget {

    public static String callJson(Context context,String urlstring){

        String data=null;

        try {
            URL url = new URL(urlstring);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            // Starts the query
            conn.connect();
         InputStream stream = conn.getInputStream();

      data = convertStreamToString(stream);


         stream.close();

         }catch(SocketTimeoutException e){

             CommonMethods.createAlert(context, "Sorry, network error", "");
         }
        catch (Exception e) {
            e.printStackTrace();
         }

        return data;

    }

    static String convertStreamToString(java.io.InputStream is) {
          java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
          return s.hasNext() ? s.next() : "";
       }

}


回答2:

Can you try the below code,if it helps.

  HttpURLConnection urlConnection = null;
    URL url = null;
    JSONObject object = null;
    InputStream inStream = null;
    try {
        url = new URL(urlString.toString());
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.connect();
        inStream = urlConnection.getInputStream();
        BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
        String temp, response = "";
        while ((temp = bReader.readLine()) != null) {
            response += temp;
        }
        object = (JSONObject) new JSONTokener(response).nextValue();
    } catch (Exception e) {
        this.mException = e;
    } finally {
        if (inStream != null) {
            try {
                // this will close the bReader as well
                inStream.close();
            } catch (IOException ignored) {
            }
        }
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }


回答3:

Try this code. This worked for me.

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;


public class ServerTest extends Activity {

    private String TAG = "test";
    private String url = "http://webkarinca.com/sample.json";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        new Download().execute();
    }


    public class Download extends AsyncTask<Void, Void, String>{

        @Override
        protected String doInBackground(Void... params) {
            String out = null;

            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();

                final HttpParams httpParameters = httpClient.getParams();

                HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
                HttpConnectionParams.setSoTimeout(httpParameters, 15000);

                HttpGet httpPost = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();

                out = EntityUtils.toString(httpEntity, HTTP.UTF_8);

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

            return out;
        }


        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            Log.e(TAG, result);
        }
    }
}

Also make sure you have added this to manifest,

<uses-permission android:name="android.permission.INTERNET" />

and also make sure you are connected to the internet.