Android Http获取请求

时间:2015-03-24 05:31:42

标签: java android http

我是android开发的新手。我正在尝试向URL发送GET请求。我写了下面的代码。

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;

}

我已经把进口头放在了班上。他们在那里

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

它不起作用,在“问题”部分显示为警告

不推荐使用HttpGet类型 不推荐使用HttpResponse类型

4 个答案:

答案 0 :(得分:1)

尝试一下。它对我有用。

首先必须在 fscanf()

上实施此操作
istream::operator>>()

然后,使用此方法

build.gradle: app

最后,调用 implementation("com.squareup.okhttp3:okhttp:4.8.0")

    String run(String url) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

答案 1 :(得分:0)

试试这个

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 :(得分:0)

如果有帮助,您可以尝试以下代码吗?

  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 :(得分:0)

试试这段代码。这对我有用。

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);
        }
    }
}

还要确保已将此添加到清单

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

并确保您已连接到互联网。