我正在尝试使用post请求在cloudant数据库中创建新文档我已经附加了我的android代码,请让我知道应该怎么做才能创建文档并在文档中插入两个值,我已附加了我的代码我得到403作为回应。
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private String url = "https:bluemix.cloudant.com/databasename/documentname";
private String REV;
enter code here
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void postreq(View view) {
HashMap<String, Object> map = new HashMap<String, Object>();
//data in document
map.put("_id", "123");
map.put("value1", "1567");
map.put("value2", "1545");
JsonObjectRequest jar1 = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(map), new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject = new JSONObject(response.toString());
REV = jsonObject.getString("rev");
} catch (JSONException e) {
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Json Error Res: ", "" + error);
}
}){
@Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
String credentials = "abcd:XYZ";
//key:Password
String auth = "Basic "
+ Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
// Log.e("qqqq", auth);
params.put("Authorization", auth);
params.put("Content-Type", "application/json");
params.put("Accept","application/json");
return params;
}
};
RequestQueue req = Volley.newRequestQueue(this);
req.add(jar1);
}}
先谢谢。
答案 0 :(得分:1)
不确定这是否是问题中的拼写错误,但您的网址看起来格格不入。您可能想要确认该URL。在创建新文档时,POST的URL应采用https://$ACCOUNT.cloudant.com/$DATABASE
的形式(您的网址包含额外的/documentname
)。
请参阅https://console.ng.bluemix.net/docs/services/Cloudant/api/document.html#create