如何设置内容类型和接受角度2获取错误415不支持的媒体类型

时间:2016-02-27 03:35:38

标签: http service angular

如何在angular2中设置Content-Type和Accept?

我正在尝试在标头中发送内容类型(application / json)的帖子 但是对于某些原因它不发送,它总是发送文本/普通; charset =内容类型的UTF-8 当我尝试进行REST服务调用时,我得到415不支持的媒体类型。我想我需要正确地设置类型和内容类型,它不会从代码中设置 我是什么 在我们下方标题请求

Accept  
text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding 
gzip, deflate
Accept-Language 
en-US,en;q=0.5
Content-Length  
13
Content-Type    
text/plain; charset=UTF-8
Host    
enrova.debug-zone.com:8000
Origin  
http://localhost:8000
Referer 
http://localhost:8000/add
User-Agent  
Mozilla/5.0 (Windows NT 10.0; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0

代码低于

    import {Component, View} from 'angular2/angular2';
    import { Inject} from 'angular2/di';
    import {Http} from 'angular2/http';

    export class AchievementsService {
        constructor( @Inject(Http) private http: Http) {        
        }

        getAchievementsOfType(type: string) : any {
            var path = '/api/achievements/' + type;
            return this.http.get(path);
        }

        getAllAchievements() : any {
            var path = '/api/achievements';
            return this.http.get(path);
        }

        addAnAchievement(newAchievement) {

            //var path = '/api/achievements';
            var path = 'http://test.com:8000/branch';
            return this.http.post('http://test.com:8000/branch', JSON.stringify(newAchievement),{
            headers: { 'Content-Type': 'application/json; charset=utf-8'}  });

    }

**Calling Class**


 import {Component, View} from 'angular2/angular2';
    import { _settings } from '../../settings'
    import {FormBuilder, Validators, formDirectives, ControlGroup} from 'angular2/forms';
    import {Inject} from 'angular2/di';
    import {Router} from 'angular2/router';
    import {AchievementsService} from '../../services/achievementsService';

    @Component({
      selector: 'add',
      injectables: [FormBuilder]
    })
    @View({
      templateUrl: _settings.buildPath + '/components/add/add.html',
      directives: [formDirectives]
    })
    export class Add {
      addAchievementForm: any;

      constructor( @Inject(FormBuilder) private formBuilder: FormBuilder,
        @Inject(Router) private router: Router,
        @Inject(AchievementsService) private achievementsService: AchievementsService) {

        this.addAchievementForm = formBuilder.group({
            name: ['']

        });
      }
    // This is the funtion that call post call written in achievementsService.ts
      addAchievement() {
        this.achievementsService.addAnAchievement(this.addAchievementForm.value)
          .map(r => r.json())
          .subscribe(result => {
            this.router.parent.navigate('/');
          });


      }
    }

3 个答案:

答案 0 :(得分:53)

这是一种更清洁的方式,用Angular2文档(https://angular.io/docs/ts/latest/guide/server-communication.html)编写。

import {Headers, RequestOptions} from 'angular2/http';

let body = JSON.stringify({ 'foo': 'bar' });
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });

return this.http.post(url, body, options)
                .map(res =>  res.json().data)
                .catch(this.handleError)

请注意,我认为只有POST查询才需要这样做。

答案 1 :(得分:6)

首先,你正在使用来自angular2/angular2的错误导入,现在angular2现在处于测试版状态,因此几乎所有导入都已更改。阅读所有进口清单的答案。

https://stackoverflow.com/a/34440018/5043867

然后根据我的理解,你想使用REST Api调用Post请求我认为你要发送content type='application/json'所以你必须通过将其附加到Header来发送它{i}我发布的示例使用标题来使用如下所示的内容类型。

 import {Component, View, Inject} from 'angular2/core';
 import {Http} from 'angular2/http';

PostRequest(url,data) {
        this.headers = new Headers();
        this.headers.append("Content-Type", 'application/json');
        this.headers.append("Authorization", 'Bearer ' + localStorage.getItem('id_token'))

        this.requestoptions = new RequestOptions({
            method: RequestMethod.Post,
            url: url,
            headers: this.headers,
            body: JSON.stringify(data)
        })

        return this.http.request(new Request(this.requestoptions))
            .map((res: Response) => {
                if (res) {
                    return [{ status: res.status, json: res.json() }]
                }
            });
}

我假设使用PostRequest作为方法名称的虚拟示例。有关HTTP和REST API调用的更多详细信息,请参阅此处: https://stackoverflow.com/a/34758630/5043867

答案 2 :(得分:2)

对于Angular 5.2.9版本

private static final String DB_NAME="Favorites.db";
private static final int DB_VER=1;

public Database(Context context) {
    super(context, DB_NAME, null, DB_VER);


    try{
        String myPath = context.getFilesDir().getAbsolutePath(); // also check the extension of you db file
        File dbfile = new File(myPath);
        if(dbfile.exists()){
        Toast.makeText(context, "database exists", Toast.LENGTH_LONG).show();
            Toast.makeText(context, ""+myPath, Toast.LENGTH_SHORT).show();
        }else{
        Toast.makeText(context, "cant find database", Toast.LENGTH_LONG).show();
            Toast.makeText(context, ""+myPath, Toast.LENGTH_SHORT).show();
        }
    }
    catch(SQLiteException e){
        System.out.println("Database doesn't exist");
    }
}

public void addToFavorites(String loadId, String loadName, String loadDetail, String loadNumber, String loadDuration, String loadAmount, String loadParent){
    SQLiteDatabase db = getReadableDatabase();
    String query = String.format("INSERT INTO Favorites(LoadId, LoadName, LoadDetail, LoadNumber, LoadDuration, LoadAmount, LoadParent) VALUES('%s','%s','%s','%s','%s','%s','%s');", loadId, loadName, loadDetail, loadNumber, loadDuration, loadAmount, loadParent);
    db.execSQL(query);
}

public void removeFromFavorites(String loadId){
    SQLiteDatabase db = getReadableDatabase();
    String query = String.format("DELETE FROM Favorites WHERE LoadId='%s';", loadId);
    db.execSQL(query);
}

public boolean isFavorite(String loadId){
    SQLiteDatabase db = getReadableDatabase();
    String query = String.format("SELECT * FROM Favorites WHERE LoadId='%s';", loadId);
    Cursor cursor = db.rawQuery(query,null);
    if(cursor.getCount() <= 0){
        cursor.close();
        return false;
    }
    cursor.close();
    return true;
}

public Cursor getInformation(Database database){
    SQLiteDatabase db = database.getReadableDatabase();
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    String[] columns = {"LoadId", "LoadParent"};

    String sqlTable = "Favorites";
    qb.setTables(sqlTable);

    Cursor CR = qb.query(db,columns,null,null,null,null,null);
    return CR;
}

public List<LoadFavorites> getFavorites(){
    SQLiteDatabase db = getReadableDatabase();
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    String[] sqlSelect = {"LoadId", "LoadName", "LoadDetail", "LoadNumber", "LoadDuration", "LoadAmount", "LoadParent"};
    String sqlTable = "Favorites";

    qb.setTables(sqlTable);
    Cursor c = qb.query(db,sqlSelect,null,null,null,null,null);

    final List<LoadFavorites> result = new ArrayList<>();
    if(c.moveToFirst()){
        do{
            result.add(new LoadFavorites(c.getString(c.getColumnIndex("LoadId")),
                    c.getString(c.getColumnIndex("LoadName")),
                    c.getString(c.getColumnIndex("LoadDetail")),
                    c.getString(c.getColumnIndex("LoadNumber")),
                    c.getString(c.getColumnIndex("LoadDuration")),
                    c.getString(c.getColumnIndex("LoadAmount")),
                    c.getString(c.getColumnIndex("LoadParent"))
                    ));
        }while(c.moveToNext());
    }
    return result;
}}