Android volley error request code 415 with Rest API?

匿名 (未验证) 提交于 2019-12-03 02:16:02

问题:

Server side:

    import flask      import flask.ext.sqlalchemy      import flask.ext.restless      app = flask.Flask(__name__)      app.config['DEBUG'] = True      app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'      SQLALCHEMY_TRACK_MODIFICATIONS=True     db = flask.ext.sqlalchemy.SQLAlchemy(app)      class Person(db.Model):          id = db.Column(db.Integer, primary_key=True)         name = db.Column(db.Unicode, unique=True)         birth_date = db.Column(db.Date)     class Computer(db.Model):          id = db.Column(db.Integer, primary_key=True)         name = db.Column(db.Unicode, unique=True)         vendor = db.Column(db.Unicode)         purchase_time = db.Column(db.DateTime)         owner_id = db.Column(db.Integer, db.ForeignKey('person.id'))         owner = db.relationship('Person', backref=db.backref('computers',                                                              lazy='dynamic'))      db.create_all()      manager = flask.ext.restless.APIManager(app, flask_sqlalchemy_db=db)      manager.create_api(Person, methods=['GET', 'POST', 'DELETE'])      manager.create_api(Computer, methods=['GET'])      app.run(host='0.0.0.0', port=5000, debug=True) 

Client Side :

Using volley post

 RequestQueue queue = Volley.newRequestQueue(this);          StringRequest postRequest = new StringRequest(Request.Method.POST, url,                 new Response.Listener<String>()                 {                     @Override                     public void onResponse(String response) {                         // response                         Log.d("Response", response);                     }                 },                 new Response.ErrorListener()                 {                     @Override                     public void onErrorResponse(VolleyError error) {                         // error                          Log.d("Error.Response", String.valueOf(error));                     }                 }         ) {             @Override             protected Map<String, String> getParams()             {                 Map<String, String>  params = new HashMap<String, String>();                 params.put("name", "Anything");                  return params;             }         };         queue.add( postRequest );      } 

Output from log:

04-29 11:42:24.556 1890-1946/? I/Icing: Indexing done F3642025687382E430F3465743F12480D56AAC66 04-29 11:43:32.123 3147-3196/? E/Volley: [157] BasicNetwork. performRequest: Unexpected response code 415 for http://IP:5000/api/person 04-29 11:43:32.132 3147-3147/? D/Error.Response: com.android.volley.ServerError 04-29 11:45:19.365 1298-1311/? I/UsageStatsService: User[0] Flushing usage stats to disk

回答1:

provide the right content type as follows

    // Optional Parameters to pass as POST request     JSONObject js = new JSONObject();     try {         js.put("name","anything");     } catch (JSONException e) {         e.printStackTrace();     }      // Make request for JSONObject     JsonObjectRequest jsonObjReq = new JsonObjectRequest(             Request.Method.POST, url, js,             new Response.Listener<JSONObject>() {                 @Override                 public void onResponse(JSONObject response) {                     Log.d(TAG, response.toString() + " i am queen");                 }             }, new Response.ErrorListener() {                 @Override                 public void onErrorResponse(VolleyError error) {                     VolleyLog.d(TAG, "Error: " + error.getMessage());                 }         }) {          /**          * Passing some request headers          */         @Override         public Map<String, String> getHeaders() throws AuthFailureError {             HashMap<String, String> headers = new HashMap<String, String>();             headers.put("Content-Type", "application/json; charset=utf-8");             return headers;         }      };      // Adding request to request queue     Volley.newRequestQueue(this).add(jsonObjReq);  } 


回答2:

415 is the error code for wrong media type. You are sending the body or your post request in plain text when the server expects json. Find out what type of content you should send and make the post body to that type.

@Override public byte[] getBody() {     return 'your json string'.getBytes();  }  @Override public String getBodyContentType() {     return "application/json; charset=utf-8"; } 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!