Java 如何向android发送http get请求
我尝试了下面的代码和许多其他示例,但都没有成功Java 如何向android发送http get请求,java,android,http,Java,Android,Http,我尝试了下面的代码和许多其他示例,但都没有成功 HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget= new HttpGet(URL); HttpResponse response = null; try { response = httpclient.execute(httpget);
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" );
}
这是url
final String URL = "https://api.myjson.com/bins/9uyrb";
看看改装。
非常容易使用和处理一切为您。
而且它非常可靠。HttpClient是进行HTTP请求的旧方法。这是由Apache提供的,Android早已停止支持HttpClient Android 6.0版本取消了对Apache HTTP客户端的支持。如果您的应用程序正在使用此客户端,并且目标是Android 2.3 API级别9或更高,请改用HttpURLConnection类。此API效率更高,因为它通过透明压缩和响应缓存减少了网络使用,并将功耗降至最低
我建议您使用或或其他任何库,因为它们可以轻松地发出网络请求。您可以通过使用类似的改装来完成一个简单的调用 将此库添加到你的应用程序gradle 为您的呼叫创建一个接口 现在我们将使用它来调用我们的请求
我无法让它工作。问题是什么?有这么多可用的代码和库,如果你努力搜索好,你会发现这么多examples@en123洛格特请!!java.lang.IllegalStateException:目标主机不能为null,也不能在参数中设置。scheme=null,host=null,path=data1
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();
}
});
}
}