如何发送http获取请求android

时间:2017-11-06 10:45:42

标签: java android http

我尝试了以下代码和许多其他示例但我无法正常工作

            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget= new HttpGet(URL);

            HttpResponse response = null;
            try {
                response = httpclient.execute(httpget);
            } catch (IOException e) {
                e.printStackTrace();
            }

            if(response.getStatusLine().getStatusCode()==200){
                String server_response = null;
                try {
                    server_response = EntityUtils.toString(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.i("Server response", server_response );
            } else {
                Log.i("Server response", "Failed to get server response" );
            }

这是网址

 final String URL = "https://api.myjson.com/bins/9uyrb";

3 个答案:

答案 0 :(得分:0)

看一下改造。 非常容易使用,并为您处理一切。 它也非常可靠。

答案 1 :(得分:0)

HttpClient是发出HTTP请求的旧方法。这是由Apache提供的,Android早已停止支持HttpClient。

Official Documentation

  

Android 6.0版本删除了对Apache HTTP客户端的支持。如果您的应用使用此客户端并定位到Android 2.3(API级别9)或更高版本,请改用HttpURLConnection类。此API更有效,因为它通过透明压缩和响应缓存减少了网络使用,并最大限度地降低了功耗。

我建议使用VolleyRetrofit或其他任何库,因为它们可以让网络请求变得轻而易举。

答案 2 :(得分:0)

您可以像使用

那样使用改装进行简单的通话

将此库添加到您的应用程序gradle

compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.okhttp3:okhttp:3.0.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'

为您的通话设置界面

interface ApiInterface {

@GET("latest")//here is the left url part and the first part will add it later when we build retrofit object
Call<JsonObject> getResponse();//this function you have the option to name it all you need to take care is the return Object


//in case you want to use a path parameter or query parameter this commented code might help :)
//    @GET("someUrl/{id}")
//    Call<SomeResponse> getSomeCall(@Path("id") int id, @Query("queryId") String someQuery);
}

现在我们将使用它来调用我们的请求

public class MainActivity extends AppCompatActivity {


Call<JsonObject> call;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
  /**Create cache*/
    int cacheSize = 10 * 1024 * 1024; // 10 MiB
    Cache cache = new Cache(getApplication().getCacheDir(), cacheSize);
    /**cache created*/


    /**create okhttp3 object*/
    OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder()
            .cache(cache)//adding the cache object that we have created
            .addInterceptor(new Interceptor() {
                @Override
                public okhttp3.Response intercept(Chain chain) throws IOException {
                    Request originalRequest = chain.request();
                    Request.Builder request = originalRequest.newBuilder();
                    if (false)
                        request.cacheControl(CacheControl.FORCE_NETWORK);//Here you can pass FORCE_NETWORK parameter to avoid getting response from our cache

                    /**if want to control cache timeout you can use this*/
                    request.cacheControl(new CacheControl.Builder()
                            .maxAge(15, TimeUnit.MINUTES)
                            .build());

                    return chain.proceed(request.build());
                }
            });

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://api.fixer.io/") // that means base url + the left url in interface "http://api.fixer.io/latest"
            .client(okHttpClientBuilder.build())//adding okhttp3 object that we have created
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    call = retrofit.create(ApiInterface.class).getResponse();

 call.enqueue(new Callback<JsonObject>() {
        @Override
        public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
            int statusCode = response.code();
            JsonObject responseJsonObject = response.body();
            System.out.println("Response Code: " + statusCode + "\n\n\n" + "Response: \n" + responseJsonObject);

            call.cancel();
        }

        @Override
        public void onFailure(Call<JsonObject> call, Throwable t) {
            // Log error here since request failed
            Log.e("MainActivity", t.toString());
            Toast.makeText(MainActivity.this, "Error has occurred: \n" + t.toString(), Toast.LENGTH_SHORT).show();
                        }
    });

}
}