Flies applications at startup.

Created a get class:

import java.io.IOException; import okhttp3.OkHttpClient; import okhttp3.Response; public class Get { OkHttpClient client = new OkHttpClient(); String run(String url) throws IOException { okhttp3.Request request = new okhttp3.Request.Builder() .url(url) .build(); Response response = client.newCall(request).execute(); return response.body().string(); } } 

In MainActivity I call it like this:

 import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import java.io.IOException; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Get test = new Get(); try { String te123 = test.run("https://geocode-maps.yandex.ru/1.x/?geocode=E52.091002%S23.721111"); } catch (IOException e) { e.printStackTrace(); } } } 

In AndroidManifest pointed:

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

What is wrong doing?

  • Error log can be provided? - Vyacheslav Martynenko
  • better to use retrofit right away - andreich

2 answers 2

The execute method () will be executed synchronously, that is, in your case in main thread, here android and swears. Need to call asynchronously

  public void run(String url, Callback callback) { okhttp3.Request request = new okhttp3.Request.Builder() .url(url) .build(); client.newCall(request).enqueue(callback); } 

and in activit

 Get test = new Get(); test.run("https://geocode-maps.yandex.ru/1.x/?geocode=E52.091002%S23.721111", new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { //todo work with response, parse and etc... } }); 

    You execute a query synchronously, you need to put it in a separate thread for example like this

     public class Get { OkHttpClient client = new OkHttpClient(); public void run(final String url, final ResponseCallBack callback) throws IOException { new Thread(new Runnable() { @Override public void run() { okhttp3.Request request = new okhttp3.Request.Builder() .url(url) .build(); Response response = client.newCall(request).execute(); final String sResponse = response.body().string(); new Handler().post(new Runnable() { @Override public void run() { callback.onResponse(sResponse); } }); } }).start(); } } public interface ResponseCallBack { void onResponse(String response); } И в активити можно вызывать так Get test = new Get(); try { test.run("https://geocode-maps.yandex.ru/1.x/?geocode=E52.091002%S23.721111", new ResponseCallBack() { @Override public void onResponse(String response) { Log.e("onResponse", response); } }); } catch (IOException e) { e.printStackTrace(); }