我是初学者。这是我的第一个Android应用。我有问题从Android发布数据到我的Drupal服务器。我正在使用Rest api。
我可以以Drupal管理员用户身份登录,获取会话ID,会话名称和令牌。我的问题是发布数据。我认为问题是发布时的身份验证。我不知道该怎么做。
INTERNET和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上,我想发布一些数据。
这是我遇到问题的地方。我一直得到消息访问被拒绝。
如何使用结果中的会话ID,会话名称或令牌(intent.putExtra(&#34; My_result&#34;,结果) - 从登录页面)发布内容?这实际上是正确的方法吗?如果有更好的方法,请告诉我。
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 :(得分: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();
// ..
顺便说一句,你最好使用OkHttp并且执行POST请求会更简单
答案 1 :(得分: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;
}
答案 2 :(得分:0)
我解决了这个问题。我没有以正确的方式设置cookie。
urlConnection.setRequestProperty("Cookie",session_name+"="+session_id);