2016-08-09 141 views
0

我是初学者。这是我的第一个Android应用程序。我有问题从Android发布数据到我的Drupal服务器。我正在使用Rest api。Android,Rest api post error - 访问被拒绝

我可以登录为Drupal管理员用户,我得到会话ID,会话名称和令牌。我的问题是发布数据。我认为问题是在发布时进行身份验证。我不知道该怎么做。

互联网和ACCESS_NETWORK_STATE清单中

登录部分(工作)

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); 
    } 
} 


邮政一部分,而不是工作的声明。
关于SecondActivity,我想发布一些数据。 这是我遇到问题的地方。我不断收到消息访问被拒绝。

如何从结果(intent.putExtra(“My_result”,结果) - 从登录页面)使用会话ID,会话名称或令牌来发布内容?这实际上是做到这一点的正确方法吗?如果有更好的方法,请告诉我。

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); 
    } 
} 

在此先感谢

+0

您是否声明了清单文件中的Internet权限? – TilalHusain

+0

是的,在清单 – Kong

+0

中声明INTERNET和ACCESS_NETWORK_STATE访问被拒绝的错误是从服务器返回的,或者您从某个抛出的异常中获得了该错误? – TilalHusain

回答

0

我解决这个问题。我没有设置正确的方式。

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

试试这个片断:

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(); 
    // .. 

Bytheway,你最好使用OkHttp和做POST请求将简单得多

+0

不幸的是,它没有工作。 – Kong

+0

请参阅编辑答案 –

+0

令牌和会话ID如何?我不需要在标题中设置它来发布帖子吗?感谢您的建议,我会看看OkHttp – Kong

0
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; 
      }