Android, Rest api post错误-拒绝访问



我是初学者。这是我的第一个Android应用程序。我有问题发布数据到我的Drupal服务器从Android。我使用Rest api。

我可以作为Drupal管理员用户登录,我获得会话id、会话名称和令牌。我的问题是发布数据。我认为问题在于发帖时的认证。我不知道该怎么做。

在manifest

中声明了INTERNET和ACCESS_NETWORK_STATE

登录部分(Working)

 private class LoginProcess extends AsyncTask<Void, Void, String> {
   @Override
   protected String doInBackground(Void... voids) {
       String address = "http://app.flickgo.com/apistuff/user/login.json";
       HttpURLConnection urlConnection;
       String requestBody;
       Uri.Builder builder = new Uri.Builder();
       Map<String, String> params = new HashMap<>();
       params.put("username", "myUsername");
       params.put("password", "myPassword");
       // encode parameters
       Iterator entries = params.entrySet().iterator();
       while (entries.hasNext()) {
           Map.Entry entry = (Map.Entry) entries.next();
           builder.appendQueryParameter(entry.getKey().toString(), entry.getValue().toString());
           entries.remove();
       }
       requestBody = builder.build().getEncodedQuery();
       try {
           URL url = new URL(address);
           urlConnection = (HttpURLConnection) url.openConnection();
           urlConnection.setDoOutput(true);
           urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
           OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
           BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
           writer.write(requestBody);
           writer.flush();
           writer.close();
           outputStream.close();
           JSONObject jsonObject = new JSONObject();
           InputStream inputStream;
           // get stream
           if (urlConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
               inputStream = urlConnection.getInputStream();
           } else {
               inputStream = urlConnection.getErrorStream();
           }
           // parse stream
           BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
           String temp, response = "";
           while ((temp = bufferedReader.readLine()) != null) {
               response += temp;
           }
           // put into JSONObject
           jsonObject.put("Content", response);
           jsonObject.put("Message", urlConnection.getResponseMessage());
           jsonObject.put("Length", urlConnection.getContentLength());
           jsonObject.put("Type", urlConnection.getContentType());
           return jsonObject.toString();
       } catch (IOException | JSONException e) {
           return e.toString();
       }
   }
   @Override
   protected void onPostExecute(String result) {
       super.onPostExecute(result);
       //create an intent to start the ListActivity
       Intent intent = new Intent(LoginActivity.this, SecondActivity.class);
       //pass the session_id and session_name to ListActivity
       intent.putExtra("My_result", result);
       //start the ListActivity
       startActivity(intent);
   }
}


Post part, not working.
在SecondActivity上,我想发布一些数据。这就是我的问题所在。我一直收到拒绝访问的消息

我如何使用会话id,会话名称或令牌从结果(意图)。putExtra("My_result",结果)-从登录页)发布内容?这真的是正确的做法吗?如果有更好的方法,请告诉我。

private class JsonPostRequest extends AsyncTask<Void, Void, String> {
    @Override
    protected String doInBackground(Void... voids) {
        try {
            String address = "http://app.flickgo.com/apistuff/node.json";
            JSONObject json = new JSONObject();
            json.put("title", "Dummy Title");
            json.put("type", "article");
            String requestBody = json.toString();
            URL url = new URL(address);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json");
            OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
            writer.write(requestBody);
            writer.flush();
            writer.close();
            outputStream.close();
            InputStream inputStream;
            // get stream
            if (urlConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
                inputStream = urlConnection.getInputStream();
            } else {
                inputStream = urlConnection.getErrorStream();
            }
            // parse stream
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String temp, response = "";
            while ((temp = bufferedReader.readLine()) != null) {
                response += temp;
            }
            // put into JSONObject
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("Content", response);
            jsonObject.put("Message", urlConnection.getResponseMessage());
            jsonObject.put("Length", urlConnection.getContentLength());
            jsonObject.put("Type", urlConnection.getContentType());
            return jsonObject.toString();
        } catch (IOException | JSONException e) {
            return e.toString();
        }
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        Toast.makeText(LoginActivity.this, result + "Test", Toast.LENGTH_LONG).show();
        //Log.i(LOG_TAG, "POST RESPONSE: " + result);
        //mTextView.setText(result);
    }
}

Thanks in advance

试试下面的代码片段:

    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestMethod("POST");
    urlConnection.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
    wr.writeBytes(requestBody);
    wr.flush();
    wr.close();
    InputStream inputStream = urlConnection.getInputStream();
    // ..

无论如何,你最好使用OkHttp和做POST请求会简单得多

Map<String, Object> params = new HashMap<>();
params.put("username", "myUsername");
params.put("password", "myPassword");
postLogin(getApplicationContext(),"http://app.flickgo.com/apistuff/node.json",params)
public JSONObject postLogin(Context mContext, String REQUEST_URL,Map<String, Object> params) {
                JSONObject jsonObject = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL(REQUEST_URL);
                    StringBuilder postData = new StringBuilder();
                    for (Map.Entry<String, Object> param : params.entrySet()) {
                        if (postData.length() != 0) postData.append('&');
                        postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                        postData.append('=');
                        postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
                    }
                    byte[] postDataBytes = postData.toString().getBytes("UTF-8");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connection.setRequestProperty("Authorization", token); //Set your token
                    connection.setConnectTimeout(8000);
                    connection.setRequestMethod("POST");
                    connection.setUseCaches(false);
                    connection.setDoOutput(true);
                    connection.getOutputStream().write(postDataBytes);
                    connection.connect();
                    StringBuilder sb;
                    int statusCode = connection.getResponseCode();
                    if (statusCode == 200) {
                        sb = new StringBuilder();
                        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        String line;
                        while ((line = reader.readLine()) != null) {
                            sb.append(line);
                        }
                        jsonObject = new JSONObject(sb.toString());
                    }
                    connection.disconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                return jsonObject;
            }

我解决了这个问题。我没有把饼干设置正确。

urlConnection.setRequestProperty("Cookie",session_name+"="+session_id);

最新更新