获取空响应来自android中的PHP Web API

时间:2017-12-08 14:29:43

标签: java php android android-asynctask

我正在使用Asynctask用于Android Studio中的网络调用。我有php web API&s;我不知道为什么但是其中一些不在android中工作。

以下是我的AsyncTask类......

    private class AsyncAddfriend extends AsyncTask<String, String, String> {


    HttpURLConnection conn;
    URL url = null;

    @Override
    protected String doInBackground(String... params) {
        try {
            url = new URL("http://ishook.com/users/friends/send_friend_request_json/");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);


            Uri.Builder builder = new Uri.Builder()
                    .appendQueryParameter("sessionId", params[0])
                    .appendQueryParameter("UserId", params[1])
                    .appendQueryParameter("friendId", params[2]);
            String query = builder.build().getEncodedQuery();
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

        } catch (IOException e) {
            e.printStackTrace();
        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // Pass data to onPostExecute method
                return (result.toString());


            } else {

                return ("unsuccessful");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return "exception";
        } finally {
            conn.disconnect();
        }


    }
}

我在其他API上使用相同的代码,但它们都工作正常,但这个api无效。 我已经在post man中测试了这个API它的工作但是没有工作的android。

希望你能理解我的问题......

0 个答案:

没有答案