Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/221.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android/OkHttp-client.newCall(request).execute()始终返回异常_Android_Request_Okhttp - Fatal编程技术网

Android/OkHttp-client.newCall(request).execute()始终返回异常

Android/OkHttp-client.newCall(request).execute()始终返回异常,android,request,okhttp,Android,Request,Okhttp,我必须做一个android应用程序项目。起初,我尝试使用HttpURLConnection,但没有成功。因此,在与一位朋友讨论后,我尝试使用OkHttp。“responses=client.newCall(request.execute();”一直都是例外。经过长时间的搜索,我只需尝试以下代码,这是“”的教程 及。。。。。它也不起作用! 我的问题是,到底发生了什么?我目前正在Android Studio 1.5.1下开发一个4.0.3应用程序。我还添加了以下两个依赖项: // DEPENDENC

我必须做一个android应用程序项目。起初,我尝试使用HttpURLConnection,但没有成功。因此,在与一位朋友讨论后,我尝试使用OkHttp。“responses=client.newCall(request.execute();”一直都是例外。经过长时间的搜索,我只需尝试以下代码,这是“”的教程 及。。。。。它也不起作用! 我的问题是,到底发生了什么?我目前正在Android Studio 1.5.1下开发一个4.0.3应用程序。我还添加了以下两个依赖项:

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

// Class Http
public static String run(String url) throws IOException {
    try {
        OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormEncodingBuilder()
                .add("login", "Mr. X")
                .add("password", "********")
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        Response responses = null;

        try {
            Log.d("DEBUGG ", "----------------------------------");
            responses = client.newCall(request).execute();
            Log.d("DEBUGG ", "----------------------------------");
            return (responses.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
        String jsonData = responses.body().string();
        JSONObject Jobject = new JSONObject(jsonData);
        JSONArray Jarray = Jobject.getJSONArray("employees");

        for (int i = 0; i < Jarray.length(); i++) {
            JSONObject object = Jarray.getJSONObject(i);
        }
    } catch (JSONException e) {

    }
    return null;
}

// MainActivity
private TextView textView;
private Button button;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textView = (TextView)findViewById(R.id.textViewJSon);
    button = (Button)findViewById(R.id.Hit);

    textView.setText("Hello !");

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                textView.setText(Http.run("https://epitech-api.herokuapp.com/login"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

}
//依赖项
//类Http
公共静态字符串运行(字符串url)引发IOException{
试一试{
OkHttpClient=新的OkHttpClient();
RequestBody formBody=新FormEncodingBuilder()
.add(“登录”、“X先生”)
.添加(“密码”,“*******”)
.build();
Request Request=newrequest.Builder()
.url(url)
.职位(表格)
.build();
响应=空;
试一试{
Log.d(“DEBUGG”,即“-----------------------------------”);
responses=client.newCall(request.execute();
Log.d(“DEBUGG”,即“-----------------------------------”);
返回(responses.body().string());
}捕获(IOE异常){
e、 printStackTrace();
}
String jsonData=responses.body().String();
JSONObject Jobject=新的JSONObject(jsonData);
JSONArray Jarray=Jobject.getJSONArray(“员工”);
for(int i=0;i
{ANSWER} 我最终尝试使用多线程编程,就像赛义德·塞尔文(said Selvin)所说的那样,它工作得很好,所以解决方案是打开另一个线程

public static int responseCode = 0;
public static String responseString = "";

public static Thread login = new Thread(new Runnable() {
    private OkHttpClient client = new OkHttpClient();
    private String url = "https://epitech-api.herokuapp.com/login";
    private User user = User.getUser();

    public void run() {
        try {
            // Build the request
            RequestBody formBody = new FormEncodingBuilder()
                .add("login", user._login)
                .add("password", user._password)
                .build();
            Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
            Response responses = null;

            // Reset the response code
            responseCode = 0;

            // Make the request
            responses = client.newCall(request).execute();

            if ((responseCode = responses.code()) == 200) {
                // Get response
                String jsonData = responses.body().string();

                // Transform reponse to JSon Object
                JSONObject json = new JSONObject(jsonData);

                // Use the JSon Object
                user._token = json.getString("token");
            }

        } catch (IOException e) {
            responseString = e.toString();
        } catch (JSONException e) {
            responseString = e.toString();
      }
   }
});

最有可能的是,由于蜂窝,主线程中的网络操作受到限制。因此,当您已经在后台线程中时,调用
execute()
方法非常有用。但是如果您在主线程中,那么
enqueue()
将非常有用,因为它将在后台线程中处理网络请求,并在主线程中返回响应。在这种情况下,您只需传递回调即可获得响应


正如您提到的,使用Okhttp是您朋友的建议。我还想推荐你使用。它将使您的代码更好、更易于维护,并代表您处理线程。在引擎盖下,它使用Okhttp。更重要的是,由于您可以在的帮助下感受到同步体验。

您无法在主线程上运行网络IO
newCall(request).execute()
不会创建新线程…或者您可以使用
.enqueue()
在后台处理请求并获得结果。我也可以使用上面的代码。但是由于线程的原因,我的按钮onClickListener在第一次点击时不工作(第二次点击时按钮工作),但是如果我删除了线程,那么我的“responses=client.newCall(request).execute();”不工作,你有什么解决方案吗??