Android Http Get 请求

Android Http Get Request

提问人:Ongun23 提问时间:3/24/2015 最后编辑:Ongun23 更新时间:7/24/2020 访问量:8005

问:

我是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 类型已弃用

java android http

评论

0赞 Neerajlal K 3/24/2015
您是否记录了变量 json 的输出?是json对象吗?有什么例外?请提供 logcat 输出。
0赞 Ongun23 3/24/2015
在分析操作之前,数据不是来自 URL。我在获取数据步骤时遇到了问题。
0赞 Neerajlal K 3/24/2015
logcat 中的错误是什么?
0赞 Ongun23 3/24/2015
我刚刚更新了代码。此代码的输出为。屏幕
0赞 Soham 3/24/2015
你试过我的代码吗?

答:

0赞 Karthika PB 3/24/2015 #1

试试这个

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() : "";
       }

}

评论

0赞 Ongun23 3/24/2015
我对方法做了一些更改,但没有用。链接
0赞 Karthika PB 3/24/2015
你试过我的代码,它不起作用吗?请发布代码和你的错误日志以及你正在使用的 URL,你确定你正在使用的 URL 在 getmethod 中接收数据吗?
0赞 Soham 3/24/2015 #2

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

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

评论

0赞 Ongun23 3/24/2015
我将您的代码更改为单个 Web 请求方法,但它不起作用。这里是链接
0赞 Soham 3/24/2015
你能告诉我你收到什么错误消息吗?
0赞 Neerajlal K 3/24/2015 #3

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

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" />

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

1赞 Marawan Mamdouh 7/19/2020 #4

试试这个。它对我有用。

首先必须实现这一点 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();
        }
    }

最后,调用它onCreate method

run("enter your URL here");

评论

1赞 learner 7/19/2020
避免发布旧问题的答案。2015 年的 Gradle 语法会有所不同。
0赞 Marawan Mamdouh 7/23/2020
感谢您的建议,我会尽量避免这种情况。@learner